Sunday, 25 September 2016

Java Socket Programming Tutorial

What is Socket Programming?
By using socket programming, you can establish a communication between two computers. By using Java Socket programming, you can establish communication between, two java applications running on different machines.

There are two ways to establish communication between two computers.
a.   Connection-Oriented Programming
b.   Connection-less programming

By using Socket and ServerSocket classes, you can perform Connection-Orietned programming. By using DatagramSocket and DatagramPacket classes, you can perform Connection-less programming. In this post, I am going to explain connection oriented programming.

Connection-Oriented Programming
Java provides Socket and ServerSocket classes to support connection oriented programming. Following are the sequence of steps happened in connection-oriented programming.
a.   Establish the connection between two entities
b.   Perform data transmission
c.    Close the connection

Data transmission in connection oriented programming is reliable. It can guarantee that data will arrive in the same order.

Socket Class
By using Socket class, you can create a socket. A socket must know information about the server socket. For example, we should provide server IP address and port (where the server is listening).

Socket class provides following constructors to connect to server socket.

public Socket()
public Socket(Proxy proxy)
protected Socket(SocketImpl impl)throws SocketException
public Socket(String host, int port) throws UnknownHostException,IOException
public Socket(InetAddress address, int port) throws IOException
public Socket(String host, int port, InetAddress localAddr, int localPort) throws IOException
public Socket(InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException

Following are the important methods, you should know while working with socket.

Method
Description
public InputStream getInputStream() throws IOException
Returns an InputStream for this socket.
public OutputStream getOutputStream() throws IOException
Returns an output stream for this socket.
public void close() throws IOException
Close the socket
public boolean isConnected()
Returns true if the socket was successfuly connected to a server
public boolean isClosed()
Returns true if the socket has been closed

ServerSocket class
ServerSocket class is used to create server socket, it accepts the connections from client sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.

ServerSocket class provides following constructors.

ServerSocket()
ServerSocket(int port)
ServerSocket(int port, int backlog)
ServerSocket(int port, int backlog, InetAddress bindAddr)

‘backlog’ specifies the maximum queue length for incoming connection indications. If a connection indication arrives when the queue is full, the connection is refused.

Following are the important methods, you should know while working with ServerSocket.

Method
Description
public Socket accept() throws IOException
Returns the socket and establish a connection between server and client.
public void close() throws IOException
Close the socket
public boolean isClosed()
Returns true if the socket has been closed


In the below example, StringServer class is the server socket, it receives data from client sockets and convert the data to upper case and send back to client.
/**
 * Accept connections from client sockets and convert the string to uppercase.
 * 
 * @author Hari krishna
 */

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

public class StringServer {

 private int port;
 private int backlog;

 public StringServer(int port, int backlog) {
  this.port = port;
  this.backlog = backlog;
 }

 public void startService() {
  ServerSocket serverSocket = null;
  try {
   serverSocket = new ServerSocket(port, backlog);

   System.out.println("Started Listening for clients");
   while (true) {
    Socket socket = serverSocket.accept();

    DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
    String str = (String) dataInputStream.readUTF();
    System.out.println("Received string : " + str);
    String upper = str.toUpperCase();

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    out.writeUTF(upper);
    socket.close();

   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (!Objects.isNull(serverSocket)) {
    try {
     serverSocket.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }

}

Following is the client implementation.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Objects;

public class StringServerClient {
 private String hostName;
 private int port;

 public StringServerClient(String hostName, int port) {
  this.hostName = hostName;
  this.port = port;
 }

 public String processData(String message) {
  Socket client = null;

  try {
   client = new Socket(hostName, port);
   OutputStream outToServer = client.getOutputStream();
   DataOutputStream out = new DataOutputStream(outToServer);

   out.writeUTF(message);

   InputStream inFromServer = client.getInputStream();
   DataInputStream in = new DataInputStream(inFromServer);

   String result = in.readUTF();

   return result;
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   if (!Objects.isNull(client)) {
    try {
     client.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
  return null;
 }
}


Following are the test classes.
public class StringServerTest {
 public static void main(String args[]) {
  StringServer server = new StringServer(12345, 10);
  server.startService();
 }
}

public class StringServerClientTest {
 public static void main(String args[]) {
  StringServerClient client = new StringServerClient("localhost", 12345);
  String data = "Hello Good Morning";
  System.out.println("Sending \'" + data + "\' to server");

  String result = client.processData(data);
  System.out.println("Result : " + result);
 }
}


Open command prompt and run StringServerTest class.
C:>javac StringServerTest.java

C:>java StringServerTest
Started Listening for clients


Open other command prompt and run StringServerClientTest class.
C:>javac StringServerClientTest.java

C:>java StringServerClientTest
Sending 'Hello Good Morning' to server
Result : HELLO GOOD MORNING





Previous                                                 Next                                                 Home

No comments:

Post a Comment