TCP Socket Example - Basics

TCP Socket is a full duplex communication way between client and server. By full duplex it means that both client and server can send and receive at the same time.
The data is transferred as bytes but object which is serializable can be transferred because serializations means that the object convert to a piece of string and strings are arrays of characters which themselves consist of bytes.

So, we can transfer almost everything using TCP sockets.

In this example, we follow this scenario:
  1. We create a server socket which is going to listen to the port number 12345
  2. The server can respond to only one request.
  3. When a client try to connect to the server on port 12345, the server accept the connection and send the client a welcome message.
  4. The client app will show the server welcome message on the terminal and send a message back in reply.
  5. The server will show the client message and close the connection.
So in our server class, we instantiate a ServerSocket object and ask it to listen to the port 12345 and accept the first request. Then we get the client socket input and output streams and send/receive messages to/from client.  

Server Class
package tcp.socket.basic;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * http://codetoearn.blogspot.com/
 *
 * @author ehsun7b
 */
public class Server {

  public static final int port = 12345;
  private ServerSocket serverSocket;

  public void listen() {
    try {
      /* creating the serverSocket object */
      serverSocket = new ServerSocket(port);

      /* serverSocket waits for one client */
      Socket clientSocket = serverSocket.accept();

      /* getting input and output streams of the client socket */
      OutputStream outputStream = clientSocket.getOutputStream();
      InputStream inputStream = clientSocket.getInputStream();

      /* sending welcome message to the client */
      String message = "Welcome! You are connected to the "
              + serverSocket.getInetAddress()
              + " on port " + port + "\n";
      outputStream.write(message.getBytes());
      outputStream.flush();

      /* getting the client reply */
      int character = inputStream.read();

      while (character != -1 && character != '\n') {
        System.out.print((char) character);
        character = inputStream.read();        
      }

      inputStream.close();
      outputStream.close();
    } catch (IOException ex) {
      System.out.println("Error: " + ex.getMessage());
    }
  }

  /* creating new server and call it's listen method */
  public static void main(String[] args) {
    new Server().listen();
  }
}

And on the client side we are doing the reverse order. We first get the server welcome message and show it and then we send a message to the server as a reply.

Client Class 
package tcp.socket.basic;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * http://codetoearn.blogspot.com/
 *
 * @author ehsun7b
 */
public class Client {

  public static final int port = 12345;
  public static final String host = "127.0.0.1";
  private Socket socket;

  public void connect() {
    try {
      /* creating the socket and trying to connect */
      socket = new Socket(host, port);

      /* getting input and output streams of the socket */
      OutputStream outputStream = socket.getOutputStream();
      InputStream inputStream = socket.getInputStream();


      /* getting the server message */
      int character = inputStream.read();

      while (character != -1 && character != '\n') {
        System.out.print((char) character);
        character = inputStream.read();        
      }

      /* replying the server */
      String message = "I am the client and thanks for accepting me.\n";
      outputStream.write(message.getBytes());
      outputStream.flush();

      inputStream.close();
      outputStream.close();
    } catch (Exception ex) {
      System.out.println("Error: " + ex.getMessage());
    }
  }
  
  public static void main(String[] args) {
    new Client().connect();
  }
}

Note that the server program should be executed first.

Download the programs here.

No comments:

Post a Comment