/** * Concurrent Server example * Anonymous thread class example * RC - 2012/2013 (LEI - FCT/UNL) * */ import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class ConcurrentEchoServer2 { static final int PORT = 8000 ; static Socket clientS; // shared socket reference /** * MAIN - accept and handle client connections using one thread for each client * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket( PORT ); for (;;) { clientS = ss.accept(); Thread t = new Thread() { // Anonymous class Socket localSock = clientS; public void run() { try { InputStream in = localSock.getInputStream(); OutputStream out = localSock.getOutputStream(); handleClient( in, out ); localSock.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; t.start(); // handle the new client in a new thread } } /** * handleClient - handle one client using in and out streams * * @param in - stream from client * @param out - stream to client */ private static void handleClient(InputStream in, OutputStream out) { int n; byte buf[] = new byte[1024]; try { while ( (n=in.read(buf))>0 ) { // works as an EchoServer System.out.println("recebi: "+new String(buf, 0, n)); out.write(buf, 0, n); } } catch (IOException e) { System.err.println(e.getMessage()); } } }