NIO服务器无法收听客户端 [英] NIO Server not able to listen to client

查看:83
本文介绍了NIO服务器无法收听客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个简单的Java NIO服务器;向选择器注册socketChannel.因此,我希望听取客户的意见并发回一些回复.在选择器注册了socketChannel之后,即使客户端(非NIO)发送了一些数据,服务器也无法读取;然而,生成的密钥仍在迭代中.

Hi I am trying to implements a simple Java NIO server; which registers the socketChannel with the selector. Hence I wish to listen to client and send some response back. After the socketChannel is registered with the selector, even if client(non NIO) sends some data, Server is not able to read; howerver the key generated is still being iterated.

详细视图:服务器端:

**First thread**:

public void run(){ 而(true){

public void run() { while (true) {

    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(true);
    serverSocketChannel.socket().bind(inetAdressOfServer);
    SocketChannel clientChannel = serverSocketChannel.accept();
    new Listener("").addSocketChannel(clientChannel);

}}

**Second Thread**:

    static Selector selector = Selector.open();
    public boolean addSocketChannel(SocketChannel clientChannel) {

        SelectionKey key = clientSocketChannel.register(selector, selector.OP_READ|SelectionKey.OP_WRITE);              
        key.attach(new ChannelCallback(clientSocketChannel));
        return key.isValid();
    }

    public void run() {

        Set keysSet = selector.keys();
        Iterator i = keysSet.iterator();        
        while (i.hasNext()) {
            SelectionKey key = (SelectionKey) i.next();
        }

        if (key.isReadable()) {
            //read and do something
        }
    }



Client Side:

Socket socket = new Socket(serverIP, serverPort);    
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());    
dos.writeBytes(str + "\n");

NB:在单线程中完成时,相同的程序可以工作,但是以上述方式实现时,它不会监听客户端. 请帮助我解决此问题.

NB: When done in single thread, the same program works, but when implemented in the manner mentioned above causes it not to listen to client. Please help me to resolve this issue.

推荐答案

很难看到您在此处所做的事情,但是看起来好像您标记为第二线程"的东西已被两个线程使用(有些混淆)实施Runnable/扩展Thread和实际线程?).特别是,我猜测new Listener的构造并启动了一个线程.然后,您在第一个线程中调用addSocketChannel.因此,存在竞争条件.

It's very difficult to see what you have done there, but it looks as if what you have marked as "second thread" is used by both threads (some confusion over implementing Runnable/extending Thread and actual threads?). In particular, I'm guessing the new Listener constructs and starts a thread. You are then calling addSocketChannel in the first thread. Therefore, there is a race condition.

selector设为静态也是一个糟糕的主意.

Also it's a poor idea to make selector static.

这篇关于NIO服务器无法收听客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆