Java - Simple Echo Server

This code snippet demonstrates a simple echo server. The Client sends the string "Hello World" to the server and the server echo's back the string to the client.

Client

  1. import java.net.*;  
  2. import java.io.*;  
  3.   
  4. class Client{  
  5.   
  6.     public static void main(String args[]){  
  7.   
  8.         try {  
  9.             Socket skClient = new Socket( "127.0.0.1", 1234);  
  10.               
  11.             System.out.println( "Connected to server!!!");  
  12.               
  13.             OutputStreamWriter sWriter = new OutputStreamWriter(skClient.getOutputStream());  
  14.             sWriter.write( "Hello World\n");  
  15.             sWriter.flush();  
  16.               
  17.             InputStreamReader sReader = new InputStreamReader(skClient.getInputStream());  
  18.             BufferedReader bReader = new BufferedReader(sReader);  
  19.               
  20.             String serverResponse = bReader.readLine();  
  21.               
  22.             System.out.println(serverResponse);  
  23.               
  24.         }  
  25.         catch (Exception e){  
  26.             System.out.println(e.getMessage());  
  27.         }  
  28.     }  
  29. }  

Server

  1. import java.net.*;  
  2. import java.io.*;  
  3.   
  4. class Server{  
  5.   
  6.     public static void main(String args[]){  
  7.         System.out.println( "Server started");  
  8.           
  9.         try {  
  10.             ServerSocket skServer = new ServerSocket(1234);  
  11.               
  12.             while (true){  
  13.                 Socket skClient = skServer.accept();  
  14.                   
  15.                 InputStreamReader sReader = new InputStreamReader(skClient.getInputStream());  
  16.                 BufferedReader bReader = new BufferedReader(sReader);  
  17.                   
  18.                 String clientResponse = bReader.readLine();  
  19.                   
  20.                 System.out.println( "Sent from client: " + clientResponse);  
  21.                   
  22.                 OutputStreamWriter sWriter = new OutputStreamWriter(skClient.getOutputStream());  
  23.                   
  24.                 sWriter.write(clientResponse +  "\n");  
  25.                 sWriter.flush();  
  26.             }  
  27.               
  28.         }  
  29.         catch (Exception e){  
  30.             System.out.println(e.getMessage());  
  31.         }  
  32.     }  
  33. }  

No comments:

Post a Comment