TCP Program  – ECHO SERVER & CLIENT

AIM : To create a client server program to echo information using the TCP protocol echo server.

ALGORITHM

Server

  • Declare the necessary arrays and variables.
  • Set server port address using socket().
  • Get the current message.
  • Connect to the client.
  • Stop the process.

Client

  • Set the client machine address.
  • Connect to the server.
  • Read from the server the current message.
  • Display the current message.
  • Close the connection.

PROGRAM:

EchoServer:

import java.net.*;

import java.io.*;

importjava.lang.*;

public class EchoServer

{

public static DatagramSocket ds;

public static byte data[] =new byte[1024];

public static intclientport=790,serverport=720;

public static void main(String args[])throws Exception

{

String str;

InetAddressia =InetAddress.getLocalHost();

ds=new DatagramSocket(serverport);

DatagramPacketdp=new DatagramPacket(data,1024,ia,clientport);

ds.receive(dp);

String s=new String(dp.getData(),0,dp.getLength());

System.out.println(“Message  :”+ s.trim());

ds.send(new DatagramPacket(data,1024,ia,clientport));

}

}

EchoClient:

import java.net.*;

import java.io.*;

public class EchoClient

{

public static DatagramSocket ds;

public static byte data[] =new byte[1024];

public static intclientport=790,serverport=720;

public static void main(String args[])throws IOException,SocketException

{

ds=new DatagramSocket(clientport);

InetAddressia =InetAddress.getLocalHost();

String str,messageReturn,messageSend;

messageSend = new String(args[0]);

messageSend.getBytes(0,messageSend.length(),data,0);

ds.send(new DatagramPacket(data,1024,ia,serverport));

DatagramPacketdp=new DatagramPacket(data,1024);

ds.receive(dp);

messageReturn = new String (dp.getData(),0);

System.out.println(“Message Returned : “+ messageReturn.trim());

}

}

OUTPUT:

Server

D:\Networking\ECHO>javac EchoServer.java

D:\Networking\ECHO>java EchoServer

Message  :hi

Client

D:\Networking\ECHO>javac EchoClient.java

Note: EchoClient.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

D:\Networking\ECHO>java EchoClient  hi

Message Returned : hi

RESULT:

Thus the TCP EchoClient and EchoServer has been executed and verified successfully

Anu

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.