Echo Server and Client in Java

Submitted by Karthikeyan on

The echo server program in java that simply broadcasts the message received to all the clients

Echo Server Program


import java.io.*;
import java.net.*;
class echos {
    public static void main(String args[]) throws Exception
    {
        String echoin;
        ServerSocket svrsoc;
        Socket soc;
        BufferedReader br;
        try
        {
            svrsoc = new ServerSocket(2000);
            soc = svrsoc.accept();
            br = new BufferedReader (new InputStreamReader(soc.getInputStream()));
            PrintStream ps = new PrintStream(soc.getOutputStream());
            System.out.println("Connected for echo:");
            while((echoin=br.readLine())!=null)
            {
                if(echoin.equals("end"))
                {
                    System.out.println("Client disconnected");
                    br.close();
                    break;
                }
                else
                    ps.println(echoin);
            }
        } 
        catch(UnknownHostException e)
        {
            System.out.println(e.toString());
        }
        catch(IOException ioe)
        {
            System.out.println(ioe);
        }
    }    
}

Echo Client Program


import java.io.*;
import java.net.*;
class echoc {
public static void main(String args[]) throws Exception    
{
    String sockin;
    try
    {
        Socket csock = new Socket(InetAddress.getLocalHost(),2000);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader br_sock = new BufferedReader(new InputStreamReader(csock.getInputStream()));
        PrintStream ps = new PrintStream(csock.getOutputStream());
        System.out.println("Start echoing... type 'end' to terminate");
        while((sockin=br.readLine())!=null)
        {
            ps.println(sockin);
            if(sockin.equals("end"))
                break;
            else 
                System.out.println("echoed from server:"+br_sock.readLine());
            
        }
    }
catch(UnknownHostException e)
{
    System.out.println(e.toString());
    
}
catch(IOException ioe)
{
    System.out.println(ioe);
}
}
}