Presentation is loading. Please wait.

Presentation is loading. Please wait.

System Programming Practical session 11 Multiple clients server Non-Blocking I/O.

Similar presentations


Presentation on theme: "System Programming Practical session 11 Multiple clients server Non-Blocking I/O."— Presentation transcript:

1 System Programming Practical session 11 Multiple clients server Non-Blocking I/O

2 Server steps for single client (reminder) 1.Creating a ServerSocket. int listenPort = 4444; ServerSocket serverSocket = new ServerSocket(listenPort); 2.Waiting for a client. Socket clientSocket = serverSocket.accept(); 3.Once connection is established, creating input and output streams. BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream(),"UTF-8")); OutputStreamWriter out = new OutputStreamWriter( clientSocket.getOutputStream(),"UTF-8"); 4.Communicating. 5.Closing connection.

3 Server steps for handling multiple clients Creating a ServerSocket. Waiting for a client. Once connection is established: Creating input and output streams. Communicating. While(true){ } Create a new thread that performs: Connection Handler

4 Server classes – EchoServer example EchoProtocol - Defines how to respond to each received message ConnectionHandler (Implements Runnable) - Handle single connection MultipleClientProtocolServer - Handle all connections, using ConnectionHandler thread per connection.

5 1.interface ServerProtocol { 2. String processMessage(String msg); 3. boolean isEnd(String msg); 4.} 5.class EchoProtocol implements ServerProtocol { 6. private int counter; 7. public EchoProtocol() { 8. counter = 0; 9. } 10. public String processMessage(String msg) { 11. counter++; 12. if (isEnd(msg)) { 13. return new String("Ok, bye bye..."); 14. } else { 15. return new String(counter + ". Received \"" + msg ); } 16. } 17. public boolean isEnd(String msg) { 18. return msg.equals("bye"); 19. } 20.}

6 1.class ConnectionHandler implements Runnable { 2. private BufferedReader in; 3. private PrintWriter out; 4. Socket clientSocket; 5. ServerProtocol protocol; 6. public ConnectionHandler(Socket acceptedSocket, ServerProtocol p) { 7. in = null; 8. out = null; 9. clientSocket = acceptedSocket; 10. protocol = p; 11. System.out.println("Accepted connection from client"); 12. System.out.println("The client is from: " + 13. acceptedSocket.getInetAddress() + ":" + acceptedSocket.getPort()); 14. } // continued on next slide

7 1. public void run() { 2. String msg; 3. try { 4. this.initialize(); 5. } catch (IOException e) { 6. System.out.println("Error in initializing I/O"); 7. } 8. try { 9. this.process(); 10. } catch (IOException e) { 11. System.out.println("Error in I/O"); 12. } 13. System.out.println("Connection closed - bye bye..."); 14. this.close(); 15. } // continued on next slide

8 1. // Starts listening 2. public void initialize() throws IOException { 3. // Initialize I/O 4. in = new BufferedReader(new InputStreamReader( 5. clientSocket.getInputStream())); 6. out = new PrintWriter( 7. clientSocket.getOutputStream(), true); 8. System.out.println("I/O initialized"); 9. } // continued on next slide

9 1. public void process() throws IOException { 2. String msg; 3. while ((msg = in.readLine()) != null) { 4. System.out.println("Received \"" + msg + 5. "\" from client"); 6. String response = protocol.processMessage(msg); 7. if (response != null) { 8. out.println(response); 9. } 10. if (protocol.isEnd(msg)) { 11. break; 12. } 13. } 14. } // continued on next slide

10 1. // Closes the connection 2. public void close() { 3. try { 4. if (in != null) { 5. in.close(); 6. } 7. if (out != null) { 8. out.close(); 9. } 10. clientSocket.close(); 11. } catch (IOException e) { 12. System.out.println("Exception in closing I/O"); 13. } 14. } 15.} // end of ConnectionHandler

11 1.class MultipleClientProtocolServer implements Runnable { 2. ServerSocket serverSocket; 3. int listenPort; 4. public MultipleClientProtocolServer( 5. int port, ServerProtocol p) { 6. serverSocket = null; 7. listenPort = port; 8. } 9. \\ continued on next slide

12 1. public void run() { 2. try { 3. serverSocket = new ServerSocket(listenPort); 4. System.out.println("Listening..."); 5. } catch (IOException e) { 6. System.out.println("Cannot listen on " + listenPort); 7. } 8. while (true) { 9. try { 10. ConnectionHandler newConnection = new ConnectionHandler( 11. serverSocket.accept(), new EchoProtocol()); 12. new Thread(newConnection).start(); 13. } catch (IOException e) { 14. System.out.println("Failed to accept on “ + listenPort); 15. } 16. } 17. } \\ continued on next slide

13 1. public static void main(String[] args) throws IOException { 2. int port = Integer.decode(args[0]).intValue(); 3. MultipleClientProtocolServer server = new MultipleClientProtocolServer(port, new EchoProtocol()); 4. Thread serverThread = new Thread(server); 5. serverThread.start(); 6. try { 7. serverThread.join(); 8. } catch (InterruptedException e) { 9. System.out.println("Server stopped"); 10. } 11. } 12.} \\ end of MultipleClientProtocolServer

14 Non-Blocking I\O

15 How a single thread can read from several channels? ConnectionHandler Channel 1 Channel 2 Buffer 1 Buffer 2

16 Channels Channels wrap sockets, and allow non-blocking I/O. read(), write(), accept() can be non blocking. Setting up a non-blocking ServerSocketChannel listening on a specific port. int port = 9999; ServerSocketChannel ssChannel = serverSocketChannel.open(); ssChannel.configureBlocking(false); ssChannel.socket().bind(new InetSocketAddress(port));

17 Buffers ByteBuffer are buffers that hold bytes. Channels know how to read and write to buffers. final int NUM_OF_BYTES = 1024; ByteBuffer buf = ByteBuffer.allocate(NUM_OF_BYTES); From Channel to Buffer and back Creating a Buffer numBytesRead = _socketChannel.read(buf1); numBytesWritten = _socketChannel.write(buf2); Return –1 if channel is closed. Update position marker of the buffer.

18 Buffer Position Marker Initial state: position buffer After read of “something” buffer s o m e t h i n g position Buffer.flip(); buffer s o m e t h i n g position

19 Message Tokenizer Accumulates characters in a buffer. Allows returning next complete message – A message terminating with a certain string (e.g., “\n”.) Methods: public synchronized void addBytes(ByteBuffer bytes); public synchronized boolean hasMessage(); public synchronized String nextMessage()


Download ppt "System Programming Practical session 11 Multiple clients server Non-Blocking I/O."

Similar presentations


Ads by Google