Monday, February 27, 2017

Echo Client Server Socket

Following two programs are written in JAVA. You have to run Server program first, and then run client program. Server program will reply the message sent by client.


Simple Echo Server Program

import java.io.*;
import java.net.*;

public class SimpleEchoServer1 {
 public static void main(String[] args) throws IOException    {

    ServerSocket ss = new ServerSocket(123);
    Socket cs = null;     
    System.out.println ("Waiting for connection.....");
   
    cs = ss.accept();     
    System.out.println ("Waiting for input.....");

    BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
    PrintWriter out = new PrintWriter(cs.getOutputStream(),true);

    String inputLine = in.readLine();
    out.println(inputLine);
    System.out.println ("Reply sent...");

    out.close();    
    in.close();    
    cs.close();    
    ss.close();
   }
}

Output on server:

Waiting for connection.....
Waiting for input.....
Reply sent...


Simple Echo Client Program

import java.io.*;
import java.net.*;

public class SimpleEchoClient1 {
   public static void main(String[] args) throws IOException   {
         Socket s1 = new Socket("localhost", 123);
         DataInputStream is = new DataInputStream(s1.getInputStream());
         System.out.print("Enter your string:");
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         String request = br.readLine();
    
         PrintWriter out = new PrintWriter(s1.getOutputStream(),true);
         out.println(request);       
         String reply = is.readLine();
         System.out.println("Echo from Server:" + reply);
         
         out.close();           
      is.close();         
      s1.close();
   } 
}

Output on Client Screen:

Enter your string:hello
Echo from Server:hello



No comments:

Post a Comment