服务器通道Java NIO之间没有通信

时间:2017-09-06 14:49:55

标签: java server client nio

我正在学习java.nio库,并且阅读了this关于使用Selector而不是使用多个线程的文章。我正在尝试从客户端向服务器发送一个简单的字符串。当我运行这两个程序时,不会发送任何字符串。

客户端:

public void sendMessage(String message) {
    buffer = ByteBuffer.wrap(message.getBytes(Charset.forName("UTF-8")));
    try {
        client.write(buffer);
        buffer.clear();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

client& buffer是:

client = SocketChannel.open(new InetSocketAddress("localhost", portNumber));
buffer = ByteBuffer.allocate(2000);

服务器:

final int PORT = 18888;
Selector selector;
ServerSocketChannel serverSocket;
ByteBuffer buffer;
Charset charset = Charset.forName("UTF-8");
try{
    selector = Selector.open();
    serverSocket = ServerSocketChannel.open();
    serverSocket.bind(new InetSocketAddress("localhost", PORT));
    serverSocket.configureBlocking(false);
    serverSocket.register(selector, SelectionKey.OP_ACCEPT);
    buffer = ByteBuffer.allocate(2000);
    ChatProtocol chat = new ChatProtocol();

    while(true){
        selector.select();
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        Iterator iter = selectedKeys.iterator();
        while(iter.hasNext()){
            SelectionKey key =  (SelectionKey)iter.next();

            if(key.isAcceptable()){
                SocketChannel client = serverSocket.accept();
                client.configureBlocking(false);
                client.register(selector, SelectionKey.OP_READ);
            }

            if(key.isReadable()){
                SocketChannel client = (SocketChannel)key.channel();
                System.out.println("Read Started");
                client.read(buffer);
                System.out.println(charset.decode(buffer).toString());
                //chat.ProccessInput(charset.decode(buffer).toString());
                buffer.clear();
            }
        }
    }
}catch(IOException e){
    e.printStackTrace();
}

P.S还应该注意,当我关闭我的客户端时,控制台中会出现“Read Started”消息

0 个答案:

没有答案