Class Socket in Java

digitization, transformation, binary

Socket(Client) in Java

Java socket interface provides access to the standard network protocols used for communication between hosts and the Internet.

The Socket class implements stream-based, connection-oriented, reliable data communication. Although Socket objects are often used with the Transmission Control Protocol, commonly known as TCP, they are independent of the actual protocol being used. The Socket class encapsulates client logic that is common to connection-oriented protocols. Sockets are two-way data pipes that are connected on either end to an address and port number.

Ads code goes here

Sockets are a low-level programming interface for networked communications. They send streams of data between applications that may or may not be on the same host.

Java.net.Socket class represents a single side of the socket connection and either the client or server. The server uses java.net.ServerSocket class to wait for a connection from clients.

Java supports a simplified object-oriented interface to sockets that makes network communications easier.Java also provides different kinds of sockets to support two distinct classes of underlying protocols.

A Socket object uses an object that belongs to a subclass of the abstract class SocketImpl to access protocol-specific logic. A program can specify the subclass of SocketImpl that is used by passing an appropriate SocketImplFactory object to the setSocketImplFactory() method before any Socket objects are created.

This feature allows a program to create sockets that are able to accommodate such things as firewalls or even work with different protocols.

Connection-Oriented Protocol

A connection-oriented protocol establishes a connection between the sender and the receiver first. Once the connection is made, two applications can send data back and forth.

The connection stays even if no data exchange takes place. The protocol ensures that no data is lost and that always arrives in order.

A TCP/IP is a connection-oriented protocol.

Connectionless Protocol

Datagram Socket class, on the other hand, uses a connectionless protocol. A connectionless protocol is more like a postal service. Applications can send short messages to each other but it does not attempt to keep the connection open between messages.

Datagram Socket does not guarantee that the order of the message or it does not keep track if the message has been delivered or not or arrived or not.

UDP is a connection less protocol.

Socket class implements client socket for inter-process communication over network. A Socket is an end point for communication between two machines. The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create a socket appropriate to the local firewall.

The client obtains a Socket Object by instantiating one, Whereas the server obtains a Socket object from the return value of accept() method. When the Socket constructor returns, it does not instantiate a Socket object but actually tries to connect to the specified Server and port.

The constructor methods create the socket and connect to the specified host and port. We can also specify if the communication will be on the connection based Stream protocol or using a datagram protocol.

A datagram-based protocol is unreliable but faster. A Stream-based protocol is chosen by default. Once the socket is created we can use the getInputStream() for file input and getOutputStream for file output.

The structure of  class Socket is given as:

public final class java.net.Socket extends java.lang.Object{
//constructors
public Socket(InetAddress address,int port) throws IOException;
public Socket(InetAddress address,int port,boolean stream) throws IOException;
public Socket(String host,int port) throws UnknownHostException;
public Socket(String host,int port,boolean stream) throws IOException;
public Socket(String host,int port,InetAddress localAddress,int localPort) throws IOException;
public Socket(InetAddress address,int port,InetAddress loalAddress,int localPort)throws IOException;
protected Socket();
protected Socket(SocketImpl impl) thows SocketException;
//methods
public synchronized void close();//closes the Socket. This makes the socket object no longercapable of connecting again to any server.
public InetAddress getInetAddress();//this method returns the address of the other computer that this socket is connected to.
public InputStream getInputStream() throws IOException;//Returns the input stream of the Socket.The input stream is connected to the output stream of the socket.
public int getLocalPort();//returns the port the socket is bound to on the local machine.
public int getPort();//returns the port of the socket is bound to on the remote machine.
public static synchronizedvoid setSocketImplFactory(SocketImplFactory fac);
public OutputStream getOutputStream() throws IOException;//Returns the output stream 
//of the socket The output stream is connected to the input stream of the remote socket.
public SocketAddress getRemoteSocketAddress();//returns the address of the remote socket.
public void connect(SocketAddress host,int timeout) throws IOException;//This method 
//connects the socket to the specified host.This method is needed only when we 
//instantiate the Socket using the no argument constructor.
public String toString();
public static synchronized void setSocketImplFactory(SocketImplFactory fac) throws IOException;
public InetAddress getLocalAddress();
public int getSoLinger() throws SocketException;
public synchronized int getSoTimeOut() throws SocketException;
public boolean getTcpNoDelay() throws SocketException;
public void setSoLinger(boolean on,int value) throws SocketException;
public synchronized void setSoTimeout(int timeout)  throws SocketException;
public void setTcpNoDelay(boolean on) throws SocketException;
}
 

The details of the class structure are given as follows:

public Socket(String host, int port);

public Socket(String host, int port) constructor Creates a stream socket and connects it to the specified port number on the named host.It may throw IOException if an I/O error occurs while opening the socket or creating the socket.

READ  How To Find Occurrence of A Word in a String in Java

If a program has specified a socket factory, the createSocketImpl() method of that factory is called to create the
actual socket implementation. Otherwise, the constructor creates a plain socket.

Parameter
host – The name of a remote machine.
port – A port on a remote machine.

public Socket(InetAddress address, int port);

public Socket(InetAddress address, int port) constructor creates a StreamSocket and connects it to the specified port number at the specified IP address(host). If the application has specified a socket factory, the factory’s createSocketImpl() method is called to create the actual socket implementation. Otherwise, a plain socket is created. It may throw IOException if an I/O error occurs while opening the socket or creating the socket. It may also throw UnknownHostException if the host can not be resolved. It the constructor does not throw an exception, it means that the connection is successful.

If a program has specified a socket factory, the createSocketImpl() method of that factory is called to create the
actual socket implementation. Otherwise, the constructor creates a plain socket.

Parameter
address – The IP address of a remote machine.
port – A port on a remote machine.

public Socket(String host, int port, InetAddress localAddr, int localPort);

public Socket(String host, int port, InetAddress localAddr, int localPort) constructor creates a Socket and connects it to the specified port on the host at the given address.

If a program has specified a socket factory, the createSocketImpl() method of that factory is called to create the actual socket implementation. Otherwise, the constructor creates a plain socket.

Parameter
host – The name of a remote machine.
port – A port on a remote machine.
localAddr – An IP address on the localhost.
localPort – A port on the localhost.

public Socket(InetAddress address, int port,InetAddress localAddr, int localPort);

public Socket(InetAddress address, int port, InetAddress localAddr, int localPort) constructor creates a Socket and connects it to the specified port on the given host. The constructor also binds the Socket to the specified local address and port.

If a program has specified a socket factory, the createSocketImpl() method of that factory is called to create the actual socket implementation. Otherwise, the constructor creates a plain socket.

Parameter
address– The IP address of a remote machine.
port – A port on a remote machine.
localAddr – An IP address on the localhost.
localPort – A port on the localhost.

public Socket(String host, int port,boolean stream); 

public Socket(String host, int port,boolean stream) constructor creates a Socket and connects it to the specified port on the given host.

READ  Literals in Java Simplified

If the stream argument is true, a stream socket is created. Otherwise, a datagram socket is created. This constructor is deprecated now, we need to use DatagramSocket for datagrams.

If a program has specified a socket factory, the createSocketImpl() method of that factory is called to create the actual socket implementation. Otherwise, the constructor creates a plain socket.

Parameter
host – The name of a remote machine.
port – A port on a remote machine.
stream -A boolean value that indicates if this socket is a stream socket.

public Socket(InetAddress host, int port,boolean stream); 

public Socket(InetAddress host, int port, boolean stream); constructor creates a Socket and connects it to the specified port on the host at the given address.

If the stream argument is true, a stream socket is created. Otherwise, a datagram socket is created. This constructor is deprecated now, we need to use DatagramSocket for datagrams.

If a program has specified a socket factory, the createSocketImpl() method of that factory is called to create the actual socket implementation. Otherwise, the constructor creates a plain socket.

Parameter
address – The IP address of a remote machine.
port – A port on a remote machine.
stream – A boolean value that indicates if this socket is a stream socket.

protected Socket();

protected Socket() constructor creates a Socket that uses an instance of the system default SocketImpl subclass for its low-level network access.

protected Socket(SocketImpl impl);

protected Socket(SocketImpl impl) constructor creates a Socket that uses the given object for its low-level network access.

Parameter
impl – The socket implementation to use.

public static synchronized void setSocketImplFactory(SocketImplFactory fac);

public static synchronized void setSocketImplFactory(SocketImplFactory fac) method sets the SocketImplFactory. This factory produces instances of subclasses of SocketImpl that do
the low-level work of sockets. When a Socket constructor is called, the createSocketImpl() method of the factory is called to create the socket implementation.

Parameter
fac – An object that implements SocketImplFactory.

public synchronized void close();

public synchronized void close() method closes this socket, releasing any system resources it holds.

public InetAddress getInetAddress();

public InetAddress getInetAddress() method returns the IP address of the remote host to which this socket is connected.

This method returns the remote IP address to which this Socket is connected.

public InputStream getInputStream();

public InputStream getInputStream() method returns an InputStream that reads data from the socket.

This method returns an InputStream that wraps this socket.

public InetAddress getLocalAddress();

public InetAddress getLocalAddress() method returns the local address that is the origin of the socket.

This method returns the local IP address from which this Socket originates.

public int getLocalPort();

public int getLocalPort() method returns the local port number that is the origin of the socket.

This method returns the local port number from which this Socket originates.

public OutputStream getOutputStream();

public OutputStream getOutputStream() method returns an OutputStream that sends data through the socket.

This method returns an OutputStream that wraps this socket.

public int getPort();

public int getPort() method returns the port number of the remote host to which this socket is connected.

This method returns the remote port number to which this Socket is connected.

public int getSoLinger();

public int getSoLinger() method returns the close time-out value for this socket. A value of -1 or 0 indicates that close()closes the socket immediately. A value greater than 0 indicates the amount of time, in seconds, that close() blocks, waiting for unsent data to be sent.

This method returns the close time-out value for the socket.

public synchronized int getSoTimeout();

public synchronized int getSoTimeout() method returns the read time-out value for this socket. A value of zero indicates that the read() method of the associated InputStream waits indefinitely for an incoming packet, while a non-zero value indicates the number of milliseconds it waits before throwing an InterruptedIOException.

This method returns the read time-out value for the socket.

public boolean getTcpNoDelay();

public boolean getTcpNoDelay() method indicates whether Nagle’s algorithm is disabled for this socket or not. Said another way, it indicates whether the TCPNODELAY option is enabled or not.

READ  How to Create A Basic Calculator In Java Applet In Advanced Way

In essence, Nagle’s algorithm takes small outgoing packets that are closely spaced in time and combines them into larger packets. This improves overall efficiency since each packet has a certain amount of overhead; however, it does so at the expense of immediacy.

This method returns true if Nagle’s algorithm is disabled for this connection; false otherwise.

public void setSoLinger(boolean on, int val);

public void setSoLinger(boolean on, int val) method sets the close timeout value for this socket. If val is -1 or 0, or if on is false, close() closes the socket immediately. If on is true and val is greater than 0, val indicates the amount of time, in seconds, that close() blocks, waiting for unsent data to be sent.

Parameter
on – A boolean value that specifies whether or not close() blocks
val – The new close time-out value, in seconds, for this socket.

public synchronized void setSoTimeout(int timeout);

public synchronized void setSoTimeout(int timeout) method is used to set the time-out value that is used for the read() method of the corresponding InputStream. A non-zero value is the length of time, in milliseconds, that the Socket should wait for data before throwing an InterruptedIOException. A value of zero indicates that the Socket should wait indefinitely. If
the timeout value is needed, this method must be called before read().

Parameter
timeout – The new read time-out value, in milliseconds, for the socket.

public void setTcpNoDelay(boolean on);

public void setTcpNoDelay(boolean on) method specifies whether Nagle’s algorithm is disabled for this socket or not. Said another way, it determines whether the TCPNODELAY option is enabled or not.

In essence, Nagle’s algorithm takes small outgoing packets that are closely spaced in time and combines them into larger packets. This improves overall efficiency since each packet has a certain amount of overhead; however, it does so at the expense of immediacy.

Parameter
on – A boolean value that specifies whether or not to disable Nagle’s algorithm.

public String toString();

public String toString() method returns a String that contains the address and port of this Socket.

This method returns the string representation of this Socket.

Apart from these methods, the Socket class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

How to connect to the server?

A client application opens a connection to a server by constructing a socket that specifies the hostname and port number of the desired server.

try{
Socket sock=new Socket("techtravelhub.com",99);
}
catch(UnknownHostException e)
{
System.out.println("Can not find host");
}
catch(IOException e)
{
System.out.println("Error connecting to host");
}

This code attempts to connect a socket at port 99 of the host techtravelhub.com.

Now there could be two scenarios:

  1. The hostname can not be resolved. (UnknownHostException)
  2. The client socket may not be able to connect to it. (IOException)

The alternative way to use the hostname

Socket sock=new Socket("192.152.178.99",99)

Once the connection has been made,input and outputStreams can be retrieved with Socket.getInputSream() and Socket.getOutputStream() methods.

Example of client-side:

try
{
Socket client=new Socket("abc.xyz.com",9996)
InputStream in=client.getInputStream();
OutputStream out=client.getOutputStream();
//write a byte:
out.write(42);
//send a text as String with delimiter as newline
PrintStream pOut =new PrintStream(out);
pOut.println("Welcome");
//read a byte
Byte getOutput=in.read();
//Read a newline with delimiter as newline
DataInputStream din=new DataInputStream(in);
String response=din.readLine();
client.close();
}
catch(IOException e){}

The client first creates a socket for communication with the server. The socket constructor specifies the server’s hostname(“abc.xyz.com”) and a predefined port number(9996).

Once the connection is established, the client writes a single byte to the server using the OutputStream’s write method. It then wraps a PrintStream and OutputStream in order to send the text.

To read a byte from the server it uses InputStream’s read() and then creates a DataInputStream from which the client gets the String of text.

Finally, it terminates the connection with the close() method.

All these methods can generate an IOexception.

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *