Client



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

class client
{

public static void main(String args[])throws Exception
{
String str;
try
{
System.out.println("Client Side..........");
Socket socket=new Socket("localHost",5000);
BufferedReader in,inline;
PrintWriter out;
while(true)
{
inline=new BufferedReader(new InputStreamReader(System.in));
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out= new PrintWriter(socket.getOutputStream(),true);
System.out.println("Enter message:-");
str=inline.readLine();
out.println(str);
if(str.equals("quit"))
break;
else
{
str=in.readLine();
System.out.println(str);
}

}
}
catch(Exception e)
{
System.out.println("No EchoServer Found.");
}
}
}

--------------------------------------------------------------------------------------------------

Echo Server




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

class EchoServer implements Runnable
{

Socket ins;
int ci;
EchoServer(Socket ins,int i)
{
this.ins=ins;
this.ci=i;
}

public static void main(String args[])
{
try
{

ServerSocket socket=new ServerSocket(5000);
System.out.println("EchoServer Started......Waiting for Clients");
int i = 1;

Socket sock;
while(true)
{
sock=socket.accept();
Runnable r = new EchoServer(sock,i);
Thread t = new Thread(r);
t.start();
System.out.println("Client" + i+" is Connected.");
i++;

}
}
catch(Exception e)
{
//System.out.println("Cannot start EchoServer.");
}
}

public void run()
{
String str;
try
{
BufferedReader in,inline;
PrintWriter out;
inline=new BufferedReader(new InputStreamReader(System.in));
in=new BufferedReader(new InputStreamReader(ins.getInputStream()));
out= new PrintWriter(ins.getOutputStream(),true);
while(true)
{
str=in.readLine();
System.out.println("From Client"+ci+":"+str);

//str=inline.readLine();
out.println("Echo from Server:"+str);

if(str.equals("quit"))
break;
}
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("Interrupted");
}
System.out.println("Client "+ci+" is Disconnected.");
}

}




Leave a Reply