Evo jednog prostog eho servera koji cim prihvati klijenta (sa
accept()) kreira novu nit u kojoj se odvija komunikacija sa tim klijentom. Dakle, slanje i primanje podataka su nezavisni od prihvatanja klijenta, a to moze da se radi u posebnoj niti za svakog klijenta.
Code:
/*
ServerThreaded.java
-------------------
Multithreaded server listens custom port and echoes requests.
Compile with
javac ServerThreaded.java
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;
// main class accepts clients and gives them to a thread
class ServerThreaded
{
public static void main(String args[])
{
java.util.concurrent.Executor threadPool = Executors.newFixedThreadPool(3);
try
{
ServerSocket server = new ServerSocket(9000);
if (server.isBound())
{
System.out.println("main():listening...");
while (true)
{
Socket client = server.accept();
threadPool.execute(new Run(client));
}
}
}
catch (IOException e)
{
System.out.println("ServerThreaded.main():e=" + e);
}
}
}
// talks with a single client
class Run implements Runnable
{
public Run(Socket client)
{
this.client = client;
}
public void run()
{
try
{
System.out.println("this.client.getRemoteSocketAddress()=" + this.client.getRemoteSocketAddress());
// read client request
byte request[] = new byte[100];
this.client.getInputStream().read(request, 0, 100);
System.out.println("Run.run():request=" + new String(request));
// send response same as request
System.out.println("Run.run():this.client.isClosed()=" + this.client.isClosed() + ",this.client.isConnected()=" + this.client.isConnected());
this.client.getOutputStream().write(request);
this.client.close();
}
catch (IOException e)
{
System.out.println("Run.run():e=" + e);
}
}
private Socket client;
}
Valjda ce ti razresiti neke nedoumice...
Sveti Avgustin: "Dobar hrišćanin treba da se kloni matematičara i svih onih koji daju lažna proročanstva. Postoji opasnost da su matematičari već sklopili pakt sa Đavolom, da pomrače čovekov um i da ga okuju okovima pakla."