Table of Contents
A socket is an End-Point of 2 sided or two-way communication link between two PCs running on the network. For Example: If there are two people in different places who want to communicate with each other and each of them has a mobile phone. So one of them has to start the communication by dialing the person and then the other person receives the call then the connection will be established between these two. Once, the connection is established, then they can start communicating with each other by sending and accepting messages, here the mobile phones act as a socket and endpoint of communication.
How communication is done?
To communicate both devices need to have sockets at their end. Since we’re doing java programming these sockets are called java objects or socket objects. So in order to establish a connection and to send and receive messages and data, both ends need to have a socket at the sender’s end and at the receiver’s end.
How sockets are used to send and receive data?
We are going to use input and output streams
- socket input streams: to read the data.
- socket output stream: to write the data.
Let’s say we want to send data from socket 1 to socket 2. In that case, we have to use socket 1 output stream and to read data from B to A, we will use the socket as an input stream.
Learn Coding in your Language! Enroll Here!
Advantages and Disadvantages of Java Sockets
S.NO | Advantages | Disadvantages |
---|---|---|
1 | Flexible & powerful | Increased complexity cost and high-Security restrictions. |
2 | Very sufficient | Socket-based communications allow only to send packets of raw data between applications. |
3 | Updated Information can be used to send only between devices | Communication can be established only with the machine requested, not with any another machine. |
4 | Low network traffic if efficient use | Both ends should have the ability to intercept the data. |
What Is a Socket?
1: What is the default value of a boolean in Java?
Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to meet with the server on the server’s machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.
On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.
Definition:A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.
An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the server.
Learn Coding in your Language! Enroll Here!
Types of Java Sockets
Socket is the concept at the core of Java’s networking support. Socket is the basis of a modern network because the socket allows one computer to run multiple clients at the same time, as well as to provide multiple types of information. And it is achieved by using a port, which is a numbered socket on a specific machine. Now, until the client connects to the server, the server process is said to “listen” to a port. The server is allowed to host multiple clients connected to the same port number, although each session is different. In order to control multi-client connections, the server process must be multi-threaded or have other ways of multiplexing the simultaneous I/O.
Socket connection occurs via protocol. Internet Protocol (IP) is a low-level routing protocol that separates data into small packets and sends it to an address across the network. But in this there is no guarantee of the delivery of the packets to its destination. For a reliable transmit of data, there is another higher-level protocol known as Transmission Control Protocol (TCP) which manages to string together these packets robustly, sorting and retransmitting them as necessary. A third protocol, known as User Datagram Protocol (UDP), can be used directly to support fast, offline, unreliable packet transfers.
After establishing the connection, a higher-level protocol ensures, which is dependent on which port you are using. TCP/IP holds the lower 1,024 ports for certain protocols. And if you have spent enough time surfing the Internet, many of these will seem very familiar to you. Port number 23 is for Telnet; 21 for FTP; 43 is for whois;25 is for e-mail; 80 is for HTTP; 79 is for finger; 119 is for netnews – and so on. How the client should interact with the port is determined by each protocol.
Java supports the following three types of sockets:
- Stream Sockets
- Datagram Sockets
- Raw Sockets
Stream Sockets
Stream Sockets allow processes to communicate using TCP. Stream sockets provide a two-way, reliable, non-replicated stream of data with no record boundaries. It is a connection-oriented socket. Once a connection is established, data can be read and written from these sockets as streams of bytes. The socket type is SOCK_STREAM.
Stream sockets are used when we need a reliable connection to send and receive multiple messages between two network programs. Stream sockets rely on TCP to ensure that messages arrive at their destinations without errors. In practice, IP packets are likely to be lost on the network or arrive erroneous. Either way, the receiving TCP connects to the sending TCP and resends that IP packet. This establishes a reliable connection between the two stream sockets.
Stream sockets play the necessary role in the client/server programs. The client program (that is, a network-aware program that requires access to some service) attempts to create a stream socket object with the IP address of a server program’s host and the port number of the server program (that is, a network-aware program that provides a service to client programs). The client program’s stream socket initialization code passes the IP address and port number to the client host’s network-management software.
This software passes the IP address and port number (via IP) to the server host through NIC. The network-management software at the server host is attempted to read the data (via IP) from the NIC and try to verify that the server program is listening for connection requests via its stream socket on the specified port. The network-management software on the host server responds to the client host’s network-management software with a positive acknowledgment if the server program is listening. In response to the client program’s stream socket initialization code, a port number is established for the client program, the port number is passed (via the client and server hosts’ network-management software) to the server program’s stream socket (which uses that number to identify the client program to which messages will be sent), and initialization of the stream socket object is completed.
If the server program is not listening on the port, the server host network management software responds to the client host network management software with a negative acknowledgment. In response, the client program’s stream socket initialization code throws an exception object and does not establish a communication channel (it does not create a stream socket object).
Datagram Sockets
Datagram sockets allow processes to use UDP for communication. Datagram sockets support bidirectional message flow. It is a connection-less socket. A process on a datagram socket may receive messages in a different order than the order in which they are sent, and may receive duplicate messages. The record boundaries of the data are preserved. The socket type is SOCK_DGRAM.
TCP/IP-style networking is appropriate for most networking needs. It provides a serialized, predictable, reliable stream of packet data. This is not without its cost, however. TCP incorporates many state-of-the-art algorithms to deal with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This leads to a somewhat inefficient way to transport data. Datagrams provide an alternative.
Datagrams are vast amounts of information that is transmitted between machines. Once the datagram has been released for its intended purpose, there is no guarantee that it will arrive or even that someone will be there to catch it. Similarly, when the datagram is received, there is no guarantee that it hasn’t been damaged in transit or that anyone who sent it is still there to get a response.
Java implements datagrams on top of the UDP protocol by using two classes: the DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or receive the DatagramPackets.
Learn to code from industry experts! Enroll here
DatagramSocket
DatagramSocket defines four public constructors. They are shown here:
- DatagramSocket( ) throws SocketException- Creates a Datagram socket bound to any unused port on the local computer.
- DatagramSocket(int port) throws SocketException- Creates a DatagramSocket bound to the port specified by the port.
- DatagramSocket(int port, InetAddress ipAddress) throws SocketException- Constructs a DatagramSocket bound to the specified port and InetAddress.
- DatagramSocket(SocketAddress address) throws SocketException- Constructs a DatagramSocket bound to the specified SocketAddress. SocketAddress is an abstract class that is implemented by the concrete class InetSocketAddress. InetSocketAddress encapsulates an IP address with a port number. All can throw a SocketException if an error occurs while creating the socket.
DatagramSocket defines many methods. Two of the most important are send( ) and receive( ), which are shown here:
- void send(DatagramPacket packet) throws IOException- Sends the packet to the port specified by the packet.
- void receive(DatagramPacket packet) throws IOException- Waits for a packet to be received from the port specified by the packet and returns the result.
Learn Coding in your Language! Enroll Here!
Raw Sockets
Raw sockets provide ICMP (Internet Control Message Protocol) access. These sockets are usually datagram-oriented, but their exact nature depends on the interface provided by the protocol. Raw sockets are not suitable for most applications. It is provided to support the development of new communication protocols or to access more complex features of existing protocols. Only root processes can use raw sockets. The socket type is SOCK_RAW.
The main part of the Internet is the address. Every computer device on the Internet has one of its own. An Internet address is a unique identifier number for each computer on the Net. Initially, all Internet addresses were 32-bit values, classified as four 8-bit values. IPv4 (Internet Protocol, version 4) specifies this type of address. However, a new address system, called IPv6 (Internet Protocol, version 6) is already in operation. IPv6 uses a 128-bit value to represent the address, which is organized into eight 16-bit fragments. While there are a few reasons and advantages for IPv6, the chief one is that it supports address space much larger than the IPv4 does. To offer background compatibility with IPv4, IPv6 address can contain a valid IPv4 address in its lower-order 32 bits. Thus, making IPv4 upwardly compatible with IPv6. Fortunately, if you are using Java, whether we are using IPv4 or IPv6 addresses, these details are handled by the Java for us and we need not to generally worry about it. Just as the numbers of an IP address define network sequence, the Internet address’ name, i.e., domain name, defines the location of the machine in a name space.
The Interfaces and Networking Classes in Java supports TCP/IP both by extending the already established stream I/O interface and by accumulating the features required to build I/O objects across the network. TCP and UDP protocol families are both supported by Java. For reliable stream-based I/O across the network TCP is used. UDP supports a simpler, hence faster, point-to-point datagram-oriented model.
Rocksaw is a simple API that runs I/O networks using IPv4 and IPv6 in Java. It provides ICMP access. ICMP is a protocol that works on the network layer and is used by network devices to diagnose network communication issues. It determines whether the data is reaching the intended destination in a timely manner. It is crucial for error reporting and testing. ICMP a connectionless protocol: one device does not need to open a connection with another device before sending an ICMP message.
Rocksaw is the de facto standard API for multi-platform raw socket programming in Java. It has been deployed on several computing nodes as part of commercial products and custom enterprise applications. The current version of RockSaw compiles on the following 32-bit and 64-bit platforms: Linux, Windows with Cygwin/MinGW/Winsock or Visual C++, FreeBSD, and Darwin/Mac OS X. It should compile on other POSIX systems using the GNU tool chain. Raw sockets are used to generate/receive packets of a type that the kernel doesn’t explicitly support.