Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2026239
  • 博文数量: 413
  • 博客积分: 10926
  • 博客等级: 上将
  • 技术积分: 3862
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-09 18:14
文章分类

全部博文(413)

文章存档

2015年(5)

2014年(1)

2013年(5)

2012年(6)

2011年(138)

2010年(85)

2009年(42)

2008年(46)

2007年(26)

2006年(59)

分类: Java

2011-06-28 10:56:34

  1. Summary
    Just like function select/poll/epoll on other platforms.

    Classes:
    SelectableChannel (SocketChannel, ServerSocketChannel, DatagramChannel, Pipe-Pipe.SinkChannel/Pipe.SourceChannel) + Selector + SelectionKey.
  2. Client
    // Creates a non-blocking socket channel for the specified host name and port.
    // connect() is called on the new channel before it is returned.
    public static SocketChannel createSocketChannel(String hostName, int port) throws IOException {
        // Create a non-blocking socket channel
        SocketChannel sChannel = SocketChannel.open();
        sChannel.configureBlocking(false);

        // Send a connection request to the server; this method is non-blocking
        sChannel.connect(new InetSocketAddress(hostName, port));
        return sChannel;
    }


    // Create a non-blocking socket and check for connections
    try {
        // Create a non-blocking socket channel on port 80
        SocketChannel sChannel = createSocketChannel("hostname.com", 80);

        // Before the socket is usable, the connection must be completed
        // by calling finishConnect(), which is non-blocking
        while (!sChannel.finishConnect()) {
            // Do something else
        }
        // Socket channel is now ready to use
    } catch (IOException e) {
    }

  3. Server
    (Ref: )
    public class MainClass {
      public static void main(String[] args) throws IOException {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetEncoder encoder = charset.newEncoder();
        CharsetDecoder decoder = charset.newDecoder();

        ByteBuffer buffer = ByteBuffer.allocate(512);

        Selector selector = Selector.open();

        ServerSocketChannel server = ServerSocketChannel.open();
        server.socket().bind(new java.net.InetSocketAddress(8000));
        server.configureBlocking(false);
        SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT);

        for (;;) {
          selector.select();
          Set keys = selector.selectedKeys();

          for (Iterator i = keys.iterator(); i.hasNext();) {
            SelectionKey key = (SelectionKey) i.next();
            i.remove();

            if (key == serverkey) {
              if (key.isAcceptable()) {
                SocketChannel client = server.accept();
                client.configureBlocking(false);
                SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ);
                clientkey.attach(new Integer(0));
              }
            } else {
              SocketChannel client = (SocketChannel) key.channel();
              if (!key.isReadable())
                continue;
              int bytesread = client.read(buffer);
              if (bytesread == -1) {
                key.cancel();
                client.close();
                continue;
              }
              buffer.flip();
              String request = decoder.decode(buffer).toString();
              buffer.clear();
              if (request.trim().equals("quit")) {
                client.write(encoder.encode(CharBuffer.wrap("Bye.")));
                key.cancel();
                client.close();
              } else {
                int num = ((Integer) key.attachment()).intValue();
                String response = num + ": " + request.toUpperCase();
                client.write(encoder.encode(CharBuffer.wrap(response)));
                key.attach(new Integer(num + 1));
              }
            }
          }
        }
      }
    }
  4. xxx
阅读(1187) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~