Tuesday, May 24, 2016

Java Network exercise: bi-direction communication, between echo server and client

My former post show examples of Client/Server using ServerSocket and Socket, with sending message from server to client, and from client to server. This example implement a echo server to show how to do bi-directional communication.



JavaServer run a ServerSocket and wait for connection and data receiving. Once connected and data received, it send back the data to the sender.

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

public class JavaServer {

    public static void main(String[] args) {
        System.out.println("Server start");
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        
        ServerSocket serverSocket = null;
        Socket clientSocket = null;
        BufferedReader bufferedReader = null;
        PrintWriter printWriter = null;
        
        try {
            serverSocket = new ServerSocket(8000);
            System.out.println("Server port: " 
                    + serverSocket.getLocalPort());
            
            clientSocket = serverSocket.accept();
            
            //Client connected
            InputStream inputStream = clientSocket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            
            OutputStream outputStream = clientSocket.getOutputStream();
            printWriter = new PrintWriter(outputStream, true);

            String line;
            while((line = bufferedReader.readLine()) != null){
                System.out.println(line);
                printWriter.println(line);  //echo back to sender
            };
            
        } catch (IOException ex) {
            System.err.println(ex.toString());
        }finally{
            
            if(printWriter != null){
                printWriter.close();
                System.out.println("printWriter closed");
            }
            
            if(bufferedReader != null){
                try {
                    bufferedReader.close();
                    System.out.println("bufferedReader closed");
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
            
            if(clientSocket != null){
                try {
                    clientSocket.close();
                    System.out.println("clientSocket closed");
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
            
            if(serverSocket != null){
                try {
                    serverSocket.close();
                    System.out.println("serverSocket closed");
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
            
        }
        
    }
    
}


JavaClient make connection to server and send something, and wait for any data received.

JavaClient .java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class JavaClient {

    public static void main(String[] args) {
        System.out.println("Run Client");
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        
        if(args.length != 2){
            System.out.println("usage: java client <port> <something>");
            System.exit(1);
        }
        
        int port = isParseInt(args[0]);
        if(port == -1){
            System.out.println("usage: java client <port> <something>");
            System.out.println("<port>: integer");
            System.exit(1);
        }
        
        Socket socket = null;
        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        
        try {
            /*
            IP is hard coded, Local Loopback = "127.0.0.1"
            Port is user entry
            */
            socket = new Socket("127.0.0.1", port);
            System.out.println("Connected...");
            
            OutputStream outputStream = socket.getOutputStream();
            printWriter = new PrintWriter(outputStream, true);
            
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = 
                    new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            
            printWriter.println(args[1]);
            
            String line;
            while((line = bufferedReader.readLine()) != null){
                System.out.println(line);
            };
            
        } catch (IOException ex) {
            System.out.println(ex.toString());
        } finally{
            
            if(bufferedReader != null){
                try {
                    bufferedReader.close();
                    System.out.println("bufferedReader closed");
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
            
            if(printWriter != null){
                printWriter.close();
                System.out.println("printWriter closed");
            }
            
            if(socket != null){
                try {
                    socket.close();
                    System.out.println("socket closed");
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        }
        
    }
    
    private static int isParseInt(String str){
        
        int num = -1;
        try{
             num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
        }
        
        return num;
    }
    
}


In both side, press Ctrl-C to stop the program.

download filesDownload the files .

Related:
- Android version of the Client side
Java Datagram/UDP Server and Client, run on raspberry Pi

No comments: