Ex 3.a - Echo Client and Echo Server

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Echo client and Echo server using TCP Sockets

Aim:

To write a Java program to implement Echo Client and Echo Server using TCP sockets.

Algorithm:

Server Side:

Step -1: Start.

Step -2: Import the necessary packages.

Step -3: Under EchoServer class, create a server socket to communicate with the client
using ServerSocket() constructor.

Step – 4: Accept the request from the client using accept() method.

Step – 5: Establish socket connection between client and server using BufferedReader.

Step -6: Echo the messages back to the client using PrintWriter() constructor.

Step – 7: Close the socket.

Client Side:

Step - 1: Start.

Step - 2: Import the necessary packages.

Step - 3: Under EchoClient class, create a new socket with IP address of the server system
using Socket() constructor.

Step – 4: Establish socket connection between client and server using BufferedReader.

Step - 5: Send messages to the server using getOutputStream() method.

Step – 6: Display the message that is echoed back from the server.

Step – 7: Close the socket.

Program:
EchoServer.java

import java.io.*;

import java.net.*;

public class EchoServer

public EchoServer(int pno)

try

server = new ServerSocket(pno);

catch (Exception err)

System.out.println(err);

public void serve()

try

while (true)

Socket client = server.accept();

BufferedReader r = new BufferedReader(new


InputStreamReader(client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(), true);

w.println("Welcome to the Java EchoServer. Type 'bye' to close.");

String line;

do

line = r.readLine();

if ( line != null )

w.println("Got: "+ line);

}while ( !line.trim().equals("bye") );

client.close();

catch (Exception err)

System.err.println(err);

public static void main(String[] args)

EchoServer s = new EchoServer(9999);

s.serve();

private ServerSocket server;


}

EchoClient.java

import java.io.*;

import java.net.*;

public class EchoClient

public static void main(String[] args)

try

Socket s = new Socket("10.10.16.41", 9999);

BufferedReader r = new BufferedReader(new


InputStreamReader(s.getInputStream()));

PrintWriter w = new PrintWriter(s.getOutputStream(), true);

BufferedReader con = new BufferedReader(new


InputStreamReader(System.in));

String line;

do

line = r.readLine();

if ( line != null )

System.out.println(line);

line = con.readLine();

w.println(line);

}
while ( !line.trim().equals("bye") );

catch (Exception err)

System.err.println(err);

Output:
Result:

Thus the Java program to implement Echo Client and Server using TCP sockets is
implemented and the output verified.

You might also like