Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Java Miscellaneous

Advanced Java

Java APIs & Frameworks

Java Useful Resources

Java - Socket Class with Examples



Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

When the connection is made, the server creates a socket object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.

After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.

The Java Socket class represents the socket that both the client and the server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.

Declaration

public class Socket
   extends Object
      implements Closeable

Constructors

Sr.No. Method & Description
1

public Socket()

This method creates an unconnected socket, with the system-default type of SocketImpl.

2

public Socket(String host, int port) throws UnknownHostException, IOException

This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server.

3

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

This method creates a socket and connects it to the specified remote host on the specified remote port. The Socket will also bind() to the local address and port supplied.

4

public Socket(InetAddress host, int port) throws IOException

This method is identical to the previous constructor, except that the host is denoted by an InetAddress object.

5

public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException.

This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String.

6

public Socket(Proxy proxy)

This method creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of any other settings.

When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port.

Methods

Some methods of interest in the Socket class are listed here. Notice that both the client and the server have a Socket object, so these methods can be invoked by both the client and the server.

Sr.No. Method & Description
1

void bind(SocketAddress bindpoint)

Binds the socket to a local address.

2

void close()

Closes this socket.

3

void connect(SocketAddress endpoint)

Connects this socket to the server.

4

void connect(SocketAddress endpoint, int timeout)

Connects this socket to the server with a specified timeout value.

5

SocketChannel getChannel()

Returns the unique SocketChannel object associated with this socket, if any.

6

InetAddress getInetAddress()

Returns the address to which the socket is connected.

7

InputStream getInputStream()

Returns an input stream for this socket.

8

boolean getKeepAlive()

Tests if SO_KEEPALIVE is enabled.

9

InetAddress getLocalAddress()

Gets the local address to which the socket is bound.

10

int getLocalPort()

Returns the local port number to which this socket is bound.

11

SocketAddress getLocalSocketAddress()

Returns the address of the endpoint this socket is bound to.

12

boolean getOOBInline()

Tests if SO_OOBINLINE is enabled.

13

<T> T getOption(SocketOption<T> name)

Returns the value of a socket option.

14

OutputStream getOutputStream()

Returns an output stream for this socket.

15

int getPort()

Returns the remote port number to which this socket is connected.

16

int getReceiveBufferSize()

Gets the value of the SO_RCVBUF option for this Socket, that is the buffer size used by the platform for input on this Socket.

17

SocketAddress getRemoteSocketAddress()

Returns the address of the endpoint this socket is connected to, or null if it is unconnected.

18

boolean getReuseAddress()

Tests if SO_REUSEADDR is enabled.

19

int getSendBufferSize()

Get value of the SO_SNDBUF option for this Socket, that is the buffer size used by the platform for output on this Socket.

20

int getSoLinger()

Returns setting for SO_LINGER.

21

int getSoTimeout()

Returns setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity).

22

boolean getTcpNoDelay()

Tests if TCP_NODELAY is enabled.

23

int getTrafficClass()

Gets traffic class or type-of-service in the IP header for packets sent from this Socket

24

boolean isBound()

Returns the binding state of the socket.

25

boolean isClosed()

Returns the closed state of the socket.

26

boolean isConnected()

Returns the connection state of the socket.

27

boolean isInputShutdown()

Returns whether the read-half of the socket connection is closed.

28

boolean isOutputShutdown()

Returns whether the write-half of the socket connection is closed.

29

void sendUrgentData(int data)

Send one byte of urgent data on the socket.

30

void setKeepAlive(boolean on)

Enable/disable SO_KEEPALIVE.

31

void setOOBInline(boolean on)

Enable/disable SO_OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded.

32

<T> Socket setOption(SocketOption<T> name, T value)

Sets the value of a socket option.

33

void setPerformancePreferences(int connectionTime, int latency, int bandwidth)

Sets performance preferences for this socket.

34

void setReceiveBufferSize(int size)

Sets the SO_RCVBUF option to the specified value for this Socket.

35

void setReuseAddress(boolean on)

Enable/disable the SO_REUSEADDR socket option.

36

void setSendBufferSize(int size)

Sets the SO_SNDBUF option to the specified value for this Socket.

37

static void setSocketImplFactory(SocketImplFactory fac)

Sets the client socket implementation factory for the application.

38

void setSoLinger(boolean on, int linger)

Enable/disable SO_LINGER with the specified linger time in seconds.

39

void setSoTimeout(int timeout)

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.

40

void setTcpNoDelay(boolean on)

Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).

41

void setTrafficClass(int tc)

Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket.

42

void shutdownInput()

Places the input stream for this socket at "end of stream".

43

void shutdownOutput()

Disables the output stream for this socket.

44

Set<SocketOption<?>> supportedOptions()

Returns a set of the socket options supported by this socket.

45

String toString()

Converts this socket to a String.

Socket Client Example

The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.

Example

package com.tutorialspoint;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class GreetingClient {

   public static void main(String [] args) {
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      try {
         System.out.println("Connecting to " + serverName + " on port " + port);
         Socket client = new Socket(serverName, port);
         
         System.out.println("Just connected to " + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);
         
         out.writeUTF("Hello from " + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         
         System.out.println("Server says " + in.readUTF());
         client.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument −

package com.tutorialspoint;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class GreetingServer extends Thread {
   private ServerSocket serverSocket;
   
   public GreetingServer(int port) throws IOException {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
   }

   public void run() {
      while(true) {
         try {
            System.out.println("Waiting for client on port " + 
               serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            
            System.out.println("Just connected to " + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            
            System.out.println(in.readUTF());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
               + "\nGoodbye!");
            server.close();
            
         } catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
         } catch (IOException e) {
            e.printStackTrace();
            break;
         }
      }
   }
   
   public static void main(String [] args) {
      int port = Integer.parseInt(args[0]);
      try {
         Thread t = new GreetingServer(port);
         t.start();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Compile the client and the server and then start the server as follows −

$ java GreetingServer 6066
Waiting for client on port 6066...
Just connected to /127.0.0.1:49462
Hello from /127.0.0.1:49462
Waiting for client on port 6066...

Check the client program as follows −

Output

$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!
Advertisements