Home » Types of Sockets in Java

Types of Sockets in Java

by Online Tutorials Library

Types of Sockets in Java

Socket is the concept at the core of Java’s networking support. The socket paradigm was part of the 4.2BSD Berkeley UNIX release in the early 1980s. For this reason, the name Berkeley socket is used. 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.

Types of Sockets in Java

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.

Types of Sockets in Java

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, ordered, non-replicated stream of data with no record boundaries. It is 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).

TCP/IP Client Sockets

TCP/IP sockets are used to implement reliable two-way, persistent, point-to-point streaming connections between hosts on the Internet. The Java I/O system can use sockets to connect to other programs on the local system or on other systems on the Internet. It is important to note that the applet establishes a reverse socket connection to the host on which the applet is loaded. This restriction exists because it is dangerous for applets loaded through a firewall to access arbitrary systems. There are two types of TCP sockets in Java.

One for the server and one for the client. The ServerSocket class is designed as a “listener”, waiting for a client to connect before doing anything. So ServerSocket is for servers. The Socket class is for clients. It is designed to connect to a server socket and initiate a protocol exchange. This is because client sockets are most commonly used in Java applications. Creating a Socket object implicitly establishes a connection between the client and server. There is no method or constructor that explicitly exposes details about setting up this connection.

Here are the two constructors used to create a client socket:

  1. Socket(String hostName, int port) throws UnknownHostException, IOException: Creates a socket connected to the specified host and port.
  2. Socket(InetAddress ipAddress, int port) throws IOException: Creates a socket using a pre-existing InetAddress object and a port.

Socket defines multiple instance methods. For example, a Socket can always check for associated address and port information using the following methods:

  1. InetAddress getInetAddress( ): It returns the InetAddress associated with the Socket object. It returns null if the socket is not connected.
  2. int getPort( ): It returns the remote port to which the invoking Socket object is connected. It returns 0 if the socket is not connected.
  3. int getLocalPort( ): Returns the local port to which the invoking Socket object is bound. It returns -1 if the socket is not bound.
  4. InputStream getInputStream( ) throws IOException: Returns the InputStream associated with the invoking socket.
  5. OutputStream getOutputStream( ) throws IOException: Returns the OutputStream associated with the invoking socket.
  6. connect( ): Allows you to specify a new connection
  7. isConnected( ): Returns true if the socket is connected to a server
  8. isBound( ): Returns true if the socket is bound to an address
  9. isClosed( ): Returns true if the socket is closed.

The following program provides a simple socket example. Opens a connection to a “whois” port (port 43) of the InterNIC server, sends command-line argument to the socket, and prints the returned data. The InterNIC will try find the argument by the registered Internet domain name, and then send back the IP address and contact information for that site.

Example of Stream Socket

WhoisClient.java

Output:

Types of Sockets in Java

Here is how the program works. First, the socket is constructed to compile the host name “internic.net” and the port number 43, which is an online site that handles the port 43 whois requests. In addition, both input and output streams are opened on the socket. Then, the string is constructed that contains the name of the web site we want to get information. The response is read by inputting from the socket, and the results are displayed.

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.

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.

Other methods give you access to various attributes associated with a DatagramSocket.

Here is a sampling:

  • InetAddress getInetAddress( ): If the socket is connected, then the address is returned. Otherwise, null is returned.
  • int getLocalPort( ): It returns the number of the local port.
  • int getPort( ): Returns the number of the port to which the socket is connected. It returns -1 if the socket is not connected to a port.
  • boolean isBound( ): Returns true if the socket is bound to an address. Returns false otherwise.
  • boolean isConnected( ): Returns true if the socket is connected to a server. Returns false otherwise.
  • void setSoTimeout(int millis) throws SocketException: Sets the time-out period to the number of milliseconds passed in millis.

DatagramPacket

DatagramPacket defines several constructors. Four are shown here:

  • DatagramPacket(byte data[ ], int size) : Specifies a buffer that will receive data and the size of a packet. It is used for receiving data over a DatagramSocket.
  • DatagramPacket(byte data[ ], int offset, int size) : Allows us to specify an offset into the buffer at which data will be stored.
  • DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port) : Specifies a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent.
  • DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port) : Transmits packets beginning at the specified offset into the data.

DatagramPacket defines several methods, including those shown here, that give access to the address and port number of a packet, as well as the raw data and its length. In general, the get methods are used on packets that are received, and the set methods are used on

packets that will be sent.

  • InetAddress getAddress( ) : Returns the address of the source (for datagrams being received) or destination (for datagrams being sent).
  • byte[ ] getData( ) : Returns the byte array of data contained in the datagram. Mostly used to retrieve data from the datagram after it has been received.
  • int getLength( ) : Returns the length of the valid data contained in the byte array that would be returned from the getData( ) method. This may not equal the length of the whole byte array.
  • int getOffset( ) : Returns the starting index of the data.
  • int getPort( ) : Returns the port number.
  • void setAddress(InetAddress ipAddress) : Sets the address to which a packet will be sent. The address is specified by ipAddress.
  • void setData(byte[ ] data) : Sets the data to data, the offset to zero, and the length to the number of bytes in data.
  • void setData(byte[ ] data, int idx, int size) : Sets the data to data, the offset to idx, and the length to size.
  • void setLength(int size) : Sets the length of the packet to size.
  • void setPort(int port) : Sets the port to port.

Example of Datagram Socket

The following example implements a very simple networked communications client and server. Messages are typed into the window at the server and written across the network to the client side, where they are displayed.

WriteServer.java

This sample application is restrained by using the DatagramSocket constructor to running between two ports on the local machine. To use the program, run java WriteServer in one window; this will serve as the client. Then run java WriteServer 1, this will serve as the server. Anything that is typed in the server window will be sent to the client window after a newline is received.

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. For example, ‘www.tutoraspire.com’ is in the COM domain (reserved commercial sites); it is called ‘tutoraspire’ (after the organization name), and ‘www’ identifies a web application server. An Internet domain name is mapped to an IP address by the Domain Naming Service (DNS). This allows users to work with domain names, but the Internet works for IP addresses.

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.

A simple example of Raw Socket is PING. Ping works by sending ICMP echo packets (Internet Message Control Protocol, an IP protocol other than TCP or UDP). The kernel has built-in code that responds to echo/ping packets. It must conform to the TCP/IP specification. There is no code to create these packages because they are not needed. So, instead of creating another system call with associated code in the kernel to accomplish this, the “ping packet generator” is a user space program. It formats an ICMP echo packet and sends it out over a SOCK_RAW, waiting for a response. That is why ping runs as set-uid root.


You may also like