Sunday, July 29, 2007

Multi-threaded Socket program in Java

Hi All,

I was trying to make to make a multi-threaded Java Socket program. After a day struggle I was able to complete my program. I am in thought of sharing my experience, So I am writing this blog. Hopefully it will help all of us to better understand, how to make multi-threaded socket program in java.

Normally to make server-side socket program, i.e., A server program which responds to the client, we will code like this

ServerSocket sock=new ServerSocket(10000); //Server will run on the port 10000
Socket pSock=sock.accept();

Here sock.accept(); will accept one client connection on the server port 10000. So if we code more accept() method, then that much no. of client can connect. So the code can be re-written as

Socket pSock;
ServerSocket sock=new ServerSocket(10000);
while(true)
pSock=sock.accept();

But here the problem is program flow will stop till the next client connects to the server. So we can re-write the code like, as on every accept() spawn a thread.

Socket pSock;
ServerSocket sock=new ServerSocket(10000);
while(true)
{
pSock=sock.accept();
new NewThread(pSock); //NewThread will take care of the client-server interaction
}

See the complete program right below:

DemoServer.java:

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

public class DemoServer{
ServerSocket sock;
Socket pSock;
public DemoServer()
{

}
public void startServer() throws IOException{
sock=new ServerSocket(10000);
while(true)
{
pSock=sock.accept();
new HyperThreading(pSock);
}
}
public void stopServer() throws IOException
{
sock.close();
}
public static void main(String[] args)
{
try{
new DemoServer().startServer();
}catch(IOException e){
System.out.println(e.toString());
}
}
}
class HyperThreading extends Thread
{
Socket pSock;
BufferedReader in;
PrintWriter out;
public HyperThreading(Socket s) throws IOException
{
pSock=s;
in=new BufferedReader(new InputStreamReader(pSock.getInputStream()));
out=new PrintWriter(pSock.getOutputStream(),true);
this.start();
}
public void run()
{
try{
out.println("Welcome HCL Server");
while(!in.readLine().equalsIgnoreCase("quit"))
{
out.println("220 Ok");
}
pSock.close();
}
catch(IOException e){
System.out.println(e.toString());
}
}
}


DemoClient.java:

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

public class DemoClient {
public static void main(String[] args) throws IOException
{
Socket sock=new Socket("localhost",10000);

BufferedReader cmd=new BufferedReader(new InputStreamReader(System.in));

BufferedReader in=new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter out=new PrintWriter(sock.getOutputStream(),true);

System.out.println(in.readLine());
while(true)
{
String mesg;
out.println(cmd.readLine());
mesg=in.readLine();
if(mesg!=null)
System.out.println(mesg);
else
break;

}
sock.close();
}
}


--
Hope this helps...

You can reach me at anand.sadasivam@googlemail.com