Friday, November 13, 2015

Implement a Multi-threading application for echo server using socket programming in JAVA

PROGRAM:

import java.io.*;
import java.net.*;
import java.lang.Thread.*;
public class EchoS 
{
static int cnt;
public static void main(String args[])
{
try
{
ServerSocket sr=new ServerSocket(5155);
while(true)
{       cnt++;
Socket sc=sr.accept();
System.out.println("Client no"+cnt);
EchoH h=new EchoH(sc);
h.start();
}
}
catch(Exception e)
{
}

}
}
class EchoH extends Thread
{
Socket sc;
EchoH(Socket sc)
{
this.sc=sc;
}
public void run()
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(sc.getInputStream()));
PrintWriter pr=new PrintWriter(sc.getOutputStream(),true);
String msg;
while(true)
{
msg=br.readLine();
System.out.println("msg:"+msg);
pr.println(msg);

}
}
catch(Exception e)
{
}
finally
{
try
{
sc.close();
}
catch(Exception e)
{
}
}
}

}

Client:


import java.net.*;
import java.io.*;
public class EchoC
{
public static void main(String args[])
{
try
{
String msg;
Socket sc=new Socket("",5155);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedReader br1=new BufferedReader(new InputStreamReader(sc.getInputStream()));
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(sc.getOutputStream())),true);
System.out.println("Enter msg:");

while((msg=br.readLine())!=null)
{
out.println(msg);
System.out.println("Echo msg"+br1.readLine());

}
}
catch(Exception e)
{

}

}
}

Server:

[pict@localhost execute]$ javac EchoS.java 
[pict@localhost execute]$ java EchoS
Client no1
msg:Hi M2
Client no2
msg:hi Amol

Client1:

[pict@localhost execute]$ javac EchoC.java 
[pict@localhost execute]$ java EchoC
Enter msg:
Hi M2
Echo msgHi M2

Client2:

[pict@localhost execute]$ javac EchoC.java 
[pict@localhost execute]$ java EchoC
Enter msg:
hi Amruta
Echo msghi Amol



No comments:

Post a Comment

Perform a suitable assignment using Xen Hypervisor or equivalent open source to configure it. Give necessary GUI.

 To install kvm on Fedora:  yum install kvm  yum install virt-manager libvirt libvirt-python python-virtinst  su -c "yum install @v...