Advertisement
marlonyao

EchoServer3.java

Apr 17th, 2011
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.37 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.net.InetSocketAddress;
  3. import java.net.ServerSocket;
  4. import java.nio.ByteBuffer;
  5. import java.nio.channels.ClosedChannelException;
  6. import java.nio.channels.SelectionKey;
  7. import java.nio.channels.Selector;
  8. import java.nio.channels.ServerSocketChannel;
  9. import java.nio.channels.SocketChannel;
  10. import java.util.Iterator;
  11.  
  12.  
  13. /**
  14.  * @author marlonyao<yaolei135@gmail.com>
  15.  *
  16.  */
  17. public class EchoServer3 {
  18.     public static int DEFAULT_PORT = 7777;
  19.  
  20.     interface Handler {
  21.         void execute(Selector selector, SelectionKey key);
  22.     }
  23.  
  24.    
  25.     public static void main(String[] args) throws IOException {
  26.         System.out.println("Listening for connection on port " + DEFAULT_PORT);
  27.  
  28.         Selector selector = Selector.open();
  29.         initServer(selector);
  30.  
  31.         while (true) {
  32.             selector.select();
  33.  
  34.             for (Iterator<SelectionKey> itor = selector.selectedKeys().iterator(); itor.hasNext();) {
  35.                 SelectionKey key = (SelectionKey) itor.next();
  36.                 itor.remove();
  37.                 Handler handler = (Handler) key.attachment();
  38.                 handler.execute(selector, key);
  39.             }
  40.         }
  41.     }
  42.  
  43.     private static void initServer(Selector selector) throws IOException,
  44.             ClosedChannelException {
  45.         ServerSocketChannel serverChannel = ServerSocketChannel.open();
  46.         ServerSocket ss = serverChannel.socket();
  47.         ss.bind(new InetSocketAddress(DEFAULT_PORT));
  48.         serverChannel.configureBlocking(false);
  49.         SelectionKey serverKey = serverChannel.register(selector, SelectionKey.OP_ACCEPT);
  50.         serverKey.attach(new ServerHandler());
  51.     }
  52.    
  53.     static class ServerHandler implements Handler {
  54.         public void execute(Selector selector, SelectionKey key) {
  55.             ServerSocketChannel server = (ServerSocketChannel) key.channel();
  56.             SocketChannel client = null;
  57.             try {
  58.                 client = server.accept();
  59.                 System.out.println("Accepted connection from " + client);
  60.             } catch (IOException e) {
  61.                 e.printStackTrace();
  62.                 return;
  63.             }
  64.            
  65.             SelectionKey clientKey = null;
  66.             try {
  67.                 client.configureBlocking(false);
  68.                 clientKey = client.register(selector, SelectionKey.OP_READ);
  69.                 clientKey.attach(new ClientHandler());
  70.             } catch (IOException e) {
  71.                 if (clientKey != null)
  72.                     clientKey.cancel();
  73.                 try { client.close(); } catch (IOException ioe) { }
  74.             }
  75.         }
  76.     }
  77.    
  78.     static class ClientHandler implements Handler {
  79.         private ByteBuffer buffer;
  80.        
  81.         public ClientHandler() {
  82.             buffer = ByteBuffer.allocate(100);
  83.         }
  84.        
  85.         public void execute(Selector selector, SelectionKey key) {
  86.             try {
  87.                 if (key.isReadable()) {
  88.                     readKey(selector, key);
  89.                 } else if (key.isWritable()) {
  90.                     writeKey(selector, key);
  91.                 }
  92.             } catch (IOException e) {
  93.                 key.cancel();
  94.                 try { key.channel().close(); } catch (IOException ioe) { }
  95.             }
  96.         }
  97.        
  98.         private void readKey(Selector selector, SelectionKey key) throws IOException {
  99.             SocketChannel client = (SocketChannel) key.channel();
  100.             int n = client.read(buffer);
  101.             if (n > 0) {
  102.                 buffer.flip();
  103.                 key.interestOps(SelectionKey.OP_WRITE);     // switch to OP_WRITE
  104.             }
  105.         }
  106.        
  107.         private void writeKey(Selector selector, SelectionKey key) throws IOException {
  108.             // System.out.println("is writable...");
  109.             SocketChannel client = (SocketChannel) key.channel();
  110.             client.write(buffer);
  111.             if (buffer.remaining() == 0) {  // write finished, switch to OP_READ
  112.                 buffer.clear();
  113.                 key.interestOps(SelectionKey.OP_READ);
  114.             }
  115.         }
  116.     }
  117. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement