Download presentation
Presentation is loading. Please wait.
Published byRylan Lawry Modified over 10 years ago
1
Trådad Echo server public class ThreadedEchoServer extends Thread { Socket con; public static void main(String[] args) {... try { ServerSocket ss = new ServerSocket(port); while (true) { try { Socket s = ss.accept(); ThreadedEchoServer tes = new ThreadedEchoServer(s); tes.start(); } catch() {}... } } catch() {}...
2
Trådad Echo server (forts) public ThreadedEchoServer(Socket s) { con = s; } public void run() { try { System.out.println("New echo server threaded"); OutputStream os = con.getOutputStream(); InputStream is = con.getInputStream(); while (true) { int n = is.read(); if (n == -1) break; os.write(n); os.flush(); } } catch(){}...
3
Trådar och server’s Kostar tid att skapa en ny tråd varje gång man får en uppkoppling –Lösning: Köa socket anropen och lägg upp en pool med trådar som kan användas av klienter
4
PoolEchoServer public class PoolEchoServer extends Thread { public final static int defaultPort = 2347; ServerSocket theServer; static int num_threads = 10; public static void main(String[] args) { int port = defaultPort;... ServerSocket ss = new ServerSocket(port); for (int i = 0; i < num_threads; i++) { PoolEchoServer pes = new PoolEchoServer(ss); pes.start(); }... }
5
PoolEchoServer public PoolEchoServer(ServerSocket ss) { theServer = ss; } public void run() { while (true) { try { Socket s = theServer.accept(); System.out.println("New echo server threaded"); OutputStream os = s.getOutputStream(); InputStream is = s.getInputStream(); while (true) { int n = is.read(); if (n == -1) break; os.write(n); os.flush(); } // end while } // end try catch (IOException e) { } } // end while } // end run
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.