Friday, February 14, 2014

Simple example of TCP Client/Server communication

It's a simple example to implement TCP Client/Server in Java. To test the function, start JavaTCPServer with port number in Terminal. The server will open a ServerSocket and wait for incoming message from client. Then start JavaTCPClient with IP address and port number in another Terminal, then enter anything. The user input will be sent to JavaTCPServer via TCP socket, when JavaTCPServer receive the message, it will echo back to JavaTCPClient, then both JavaTCPServer and JavaTCPClient close the socket.

TCP Client/Server communication
TCP Client/Server communication

JavaTCPServer.java
package javatcpserver;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTCPServer {

    private static int port;
    private static ServerSocket serverSocket;

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("usage: java -jar JavaTCPServer.jar <port>");
            System.exit(1);
        }

        port = Integer.parseInt(args[0]);
        System.out.println("Port: " + port);

        Socket socket = null;
        try {
            serverSocket = new ServerSocket(port);

            socket = serverSocket.accept();
            Scanner scanner = new Scanner(socket.getInputStream());
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);

            String line = scanner.nextLine();

            System.out.println("received: " + line);
            printWriter.println("echo: " + line);
        } catch (IOException ex) {
            Logger.getLogger(JavaTCPServer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(JavaTCPServer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }

    }

}

JavaTCPClient.java
package javatcpclient;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTCPClient {

    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("usage: java -jar JavaTCPClient.jar <IP address> <port>");
            System.exit(1);
        }
        
        Socket socket = null;
        try {
            InetAddress inetAddress = InetAddress.getByName(args[0]);
            int port = Integer.parseInt(args[1]);
            
            socket = new Socket(inetAddress, port);
            System.out.println("InetAddress: " + inetAddress);
            System.out.println("Port: " + port);
            
            Scanner scanner = new Scanner(socket.getInputStream());
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
            
            Scanner userScanner = new Scanner(System.in);
            String userInput = userScanner.nextLine();
            
            printWriter.println(userInput);
            String serverEcho = scanner.nextLine();
            System.out.println(serverEcho);

        } catch (UnknownHostException ex) {
            Logger.getLogger(JavaTCPClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JavaTCPClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if( socket != null){
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(JavaTCPClient.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
}





Compare with: Simple example of UDP Client/Server communication

No comments:

Post a Comment