ในบทความที่ผ่านๆมานั้นจะเห็นว่า server จะสามารถรองรับได้แค่เพียง 1 client เท่านั้นแต่ในความเป็นจริงนั้น server ต้องรองรับการทำงานได้จากหลาย client ดังนั้นจึงต้องมีการทำงานแบบ multitask คือทำงานได้หลายๆอย่างพร้อมกัน ซึ่งในภาษาจาวานั้นก็มีคลาสหรือ interface ที่เอาไว้ทำงานหลายอย่างพร้อมกัน ซึ่งในตัวอย่างโปรแกรมภาษาจาต่อไปนี้จะใช้การสืบทอดคลาส threads[sourcecode language=”java”]
import java.io.*;
import java.net.*;
import java.util.*;
public class MultiEchoServer
{
private static ServerSocket serverSocket;
private static final int PORT = 1234;
public static void main(String[] args) throws IOException
{
try
{
serverSocket = new ServerSocket(PORT);
}
catch (IOException ioEx)
{
System.out.println(“\nUnable to set up port!”);
System.exit(1);
}
do
{
//Wait for client
Socket client = serverSocket.accept();
System.out.println(“\nNew client accepted.\n”);
//Create a thread to handle communication with
//this client and pass the constructor for this
//thread a reference to the relevant socket
ClientHandler handler = new ClientHandler(client);
handler.start(); // As usual, method call run.
}
while (true);
}
}
class ClientHandler extends Thread
{
private Socket client;
private Scanner input;
private PrintWriter output;
public ClientHandler(Socket socket)
{
//Set up reference to associated socket..
client = socket;
try
{
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(),true);
}
catch (IOException ioEx)
{
ioEx.printStackTrace();
}
}
public void run()
{
String received;
do
{
//Accept message from clienton
//the socket’s input stream..
received = input.nextLine();
//Echo message back to client on
//the socket’s output stream…
output.println(“ECHO: ” + received);
//Repeat above until ‘QUIT’ sent by client…
}
while (!received.equals(“QUIT”));
try
{
if(client!=null)
{
System.out.println(“Closing down connection..”);
client.close();
}
}
catch (IOException ioEx)
{
System.out.println(“Unable to disconnect”);
}
}
}
[/sourcecode]
จากโค้ดของโปรแกรมจาวานั้นจะเห็นว่าได้มีการสร้างคลาสขึ้นมาใหม่เพื่อจัดการกับเครื่องที่เข้ามาใช้บริการเฉพาะ นั้นก็คือ class ClientHandler extends Thread ซึ่งได้ทำการสืบทอด Thread เพื่อให้สามารถทำงานหลายๆงานได้พร้อมกันซึ่งในส่วนของ constructor ซึ่งต้องการเป็น Object ของ Socket ที่ทำการเชื่อมต่อเพื่อจะได้จัดการแต่ละเชื่อมต่อไปซึ่งคือ ClientHandler handler = new ClientHandler(client); ซึ่งจะเห็นว่าแตกต่างกับแบบเครื่องเดียวคือการสร้างคลาสในการทำงานขึ้นมาแล้วทำการสืบทอด Thread