TCP Programming with Java

04 Mar 2011 by

TCP Programming has been developed for the sake of reliability in data transmission. Unique feature of TCP is Acknowledgment scheme, Packet ordering and congestion control. These make TCP more popular in network transmission control protocol. Nowadays, the protocol dominant in the Internet is HTTP but be remembered that it relies on TCP architecture. There are several variant of TCP protocols that have been extensively researched. For example, TCP Tahoe, TCP Reno, TCP New Reno, TCP Westwood, TCP Vegas, etc. In contrast with UDP Programming, TCP is much easier.

TCP Client in Java

1. Connect to server

Socket socket = new Socket(String host, int port);

2. Read and write from socket

Write string through socket

PrintWriter out =
      new PrintWriter(socket.getOutputStream(), true);
out.println("Hello");

Read string from a socket

BufferedReader in =
      new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = in.readLine();

TCP Server in Java

1. Create server socket

ServerSocket server = new ServerSocket(PORT);

2. Wait for client to connect

Socket socket = server.accept();

3. Read and write from socket

It is done as the same client side. PrintWriter and BufferedReader will serve accordingly.

Example

I will show you a sample program of a server listening on a specific port and waiting for client to request. Once client connected, client sends “Hello” message and then server will reverse the receiving message and sends back to client.

SimpleTCPServer.java

import java.io.*;
import java.net.*;
/**
 * @author lycog
 */
public class SimpleTCPServer {
  public static void main(String[] args){
    try{
      //Create server socket listening on port 8888
      ServerSocket server = new ServerSocket(8888);

      while(true){
        System.out.println("Waiting for client to connect...");
        Socket socket = server.accept();

        //Create read/write from socket
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in =
                new BufferedReader(
                          new InputStreamReader(socket.getInputStream()));

        //client address
        InetAddress remoteIp = socket.getInetAddress();

        //Receiving from client
        String msg = in.readLine();
        System.out.println("Client " + remoteIp + " : " + msg);

        //Sending a reversed string
        msg = reverseString(msg.trim());
        out.println(msg);
      }
    }catch(IOException ioe){
      ioe.printStackTrace();
    }
  }

  private static String reverseString(String input) {
    StringBuilder buf = new StringBuilder(input);
    return buf.reverse().toString();
  }
}

SimpleTCPClient.java

import java.net.*;
import java.io.*;
/**
 * @author lycog
 */
public class SimpleTCPClient {
  public static void main(String[] args){
    try{
      Socket socket = new Socket("127.0.0.1", 8888);
      //Define read/write from socket
      PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
      BufferedReader in =
              new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));

      //Send hello message
      String msg = "Hello";
      out.println(msg);

      //Receive a reversed message
      msg = in.readLine();
      System.out.println("Server : " + msg);
    }catch(IOException ioe){
      ioe.printStackTrace();
    }
  }
}

For the sake of comparison, visit a similar program written in UDP Programming with Java article.

4 responses so far

Leave a Reply