Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Emily Diaz   on Feb 16 In Java Category.

  
Question Answered By: Corey Jones   on Feb 16

You have to use Mutithreading to handle more than one Client simultaniously..
means instead putting the Socket's action code in listener thread itself, create
a new Thread for each incoming socket & put ur handle code in that class (pass
the incoming Socket as a paramter to tht Thread)

I hv attached sample code,

To run Server,
java JServerSock

To run Clients
java JClientSock "Client 1"
java JClientSock "Client 2"
.
.
.
java JClientSock "Client n"

regards,
S.Vasanth Kumar.

SERVER CODE
============
import java.net.*;
import java.io.*;

public class JServerSock implements Runnable
{
ServerSocket ss;
Thread thrdListen;

public JServerSock()
{
try
{
ss = new ServerSocket(10000);
thrdListen = new Thread(this);
thrdListen.start();
System.out.println("Server Started Successfully!!");
}
catch(Exception ex)
{
System.out.println(ex.toString());
System.exit(1);
}
}

public void run()
{
if(Thread.currentThread() == thrdListen)
{
try
{
while(true)
{
Socket s = ss.accept();
new SocketHandle(s).start();
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
System.exit(1);
}
}
}

public static void main(String args[])
{
new JServerSock();
}


class SocketHandle extends Thread
{
Socket s;

public SocketHandle(Socket inSocket)
{
this.s = inSocket;
}

public void run()
{
try
{
while(true)
{
BufferedInputStream bin = new BufferedInputStream(s.getInputStream());
int n=-1;
byte[] b = new byte[5000];
while((n=bin.read(b,0,b.length))!=-1)
{
for(int i=0;i<n;i++)
{
System.out.print((char)b[i]);
}
}
bin.close();
s.close();
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
stop();
}
}
}
}
CLIENT CODE
===========
import java.net.*;
import java.io.*;
public class JClientSock implements Runnable
{
Thread thrdListen;
static String strClientName = "Client1";

public JClientSock()
{
try
{
thrdListen = new Thread(this);
thrdListen.start();
System.out.println("Client Started Successfully!!");
}
catch(Exception ex)
{
System.out.println(ex.toString());
System.exit(1);
}
}

public void run()
{
if(Thread.currentThread() == thrdListen)
{
try
{
Socket s = new Socket("localhost",10000);
BufferedOutputStream bOut = new BufferedOutputStream(s.getOutputStream());
while(true)
{
bOut.write((strClientName + " Request\n").getBytes());
bOut.flush();
Thread.sleep(1000);
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
System.exit(1);
}
}
}

public static void main(String args[])
{
if(args.length>0)
strClientName = args[0];

new JClientSock();
}
}

Share: 

 

This Question has 8 more answer(s). View Complete Question Thread

 


Tagged: