Friday, August 29, 2014
TCP/IP (Transmission Control Protocol/ Internet Protocol) is the protocol of the internet used to interconnect hosts. TCP/IP  provides reliable communication between 2 end points. This article provides an introduction to work with TCP/IP Sockets using Java.

A Socket is an end point of communication flow and is a combination of IP address and a port number. In the TCP/IP world processes that provide services are referred as servers and they typically create sockets and listen for any client processes to connect.

Java support two types of TCP sockets.
  1. ServerSocket - ServerSocket class is a listener which waits for client to connect. ServerSocket is used for TCP/IP servers.
  2. Socket - Socket class is for clients and they are used to connect to server sockets.

TCP/IP Server example in Java

The ServerSocket class is used to create servers. Typically we create the ServerSocket instance with the port number to be published for client connections. ServerSocket has the accept() method which waits for client connections. In the example below we use a ClientHandler thread which simply reads the message from client and writes back a message to client.

package com.sourcetricks.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class JavaServer {

  private static class ClientHandler extends Thread {

    private Socket socket;
    
    ClientHandler(Socket socket) {
      System.out.println("Client connected");
      this.socket = socket;
    }
    
    @Override
    public void run() {
      
      try {
        // Reader and writer
        BufferedReader reader = new BufferedReader
            (new InputStreamReader(socket.getInputStream()));
        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
        
        // Read message from client
        System.out.println(reader.readLine());
        
        // Write a message back to client
        writer.println("Hello from server");
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          socket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    
  }
  
  public static void main ( String[] args ) {
    final int port = 8888;
    
    try ( ServerSocket ss = new ServerSocket(port) ) {
      System.out.println("Listening ...");
      while ( true ) {
        Socket socket = ss.accept();
        new ClientHandler(socket).start();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

TCP/IP Client example in Java

The Socket class is used for client connections. The client connects on the published port of the server. Please note the usage of InetAddress class in Socket constructor. Refer to tutorials on read files in java and write files in java to better understand the usage of BufferedReader and PrintWriter. The client program in this example publishes a message to the server and prints the message received from the server.

package com.sourcetricks.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class JavaClient {

  public static void main (String[] args) {
    
    Socket socket = null;
    try {
      socket = new Socket(InetAddress.getLocalHost().getHostName(), 8888);
      
      // Reader and writer
      BufferedReader reader = new BufferedReader
          (new InputStreamReader(socket.getInputStream()));
      PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

      // Write a message to server      
      writer.println("Hello from client");
      
      // Read message from server
      System.out.println(reader.readLine());      
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        socket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
Continue to read other java tutorials from here.

0 comments :

Post a Comment

Contact Form

Name

Email *

Message *

Back to Top