1 / 5

Trådad Echo server

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();

erin-osborn
Download Presentation

Trådad Echo server

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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

More Related