Threads to Handle Socket Connections
This program is Network Server that handles socket connection
from clients. It assigns a separate thread to each new socket
connection. This is a simple server. It echos back whatever the
clients send.
import java.io.*;
import java.net.*;
class ClientHandler extends Thread
{
protected Socket incoming;
public ClientHandler (Socket incoming)
{
this.incoming = incoming;
}
public void run ()
{
try
{
BufferedReader in = new BufferedReader (new InputStreamReader (
incoming.getInputStream()));
PrintWriter out = new PrintWriter (new OutputStreamWriter (
incoming.getOutputStream()));
out.println ("Hello! This is the Java MultiEchoServer.");
out.println ("Enter BYE to exit.");
out.flush ();
while (true)
{
String str = in.readLine();
if (str == null)
{
break;
}
else
{
out.println ("Echo: " + str);
out.flush();
if (str.trim().equals("BYE"))
break;
}
}
incoming.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public class MultiEchoServer
{
public static void main (String[] args)
{
try
{
ServerSocket s = new ServerSocket (8008);
while (true)
{
Socket incoming = s.accept();
new ClientHandler (incoming).start();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}