2

使用 NIO 库在 Java 中创建一个简单的 ChatServer 让我很痛苦。想知道是否有人可以帮助我。我通过使用 SocketChannel 和 Selector 在单个线程中处理多个客户端来做到这一点。问题是:我能够接受新连接并获取它的数据,但是当我尝试发回数据时,SocketChannel 根本不起作用。在 write() 方法中,它返回一个与我传递给它的数据大小相同的整数,但客户端永远不会收到该数据。奇怪的是,当我关闭服务器应用程序时,客户端会收到数据。就像 socketchannel 维护一个缓冲区,它只有在我关闭应用程序时才会被刷新。

这里有一些更多的细节,给你更多的信息来帮助。我正在处理这段代码中的事件:

private void run() throws IOException {

    ServerSocketChannel ssc = ServerSocketChannel.open();

    // Set it to non-blocking, so we can use select
    ssc.configureBlocking( false );

    // Get the Socket connected to this channel, and bind it
    // to the listening port
    this.serverSocket = ssc.socket();
    InetSocketAddress isa = new InetSocketAddress( this.port );
    serverSocket.bind( isa );

    // Create a new Selector for selecting
    this.masterSelector = Selector.open();

    // Register the ServerSocketChannel, so we can
    // listen for incoming connections
    ssc.register( masterSelector, SelectionKey.OP_ACCEPT );

    while (true) {
        // See if we've had any activity -- either
        // an incoming connection, or incoming data on an
        // existing connection
        int num = masterSelector.select();

        // If we don't have any activity, loop around and wait
        // again
        if (num == 0) {
            continue;
        }

        // Get the keys corresponding to the activity
        // that has been detected, and process them
        // one by one
        Set keys = masterSelector.selectedKeys();
        Iterator it = keys.iterator();
        while (it.hasNext()) {
            // Get a key representing one of bits of I/O
            // activity
            SelectionKey key = (SelectionKey)it.next();

            // What kind of activity is it?
            if ((key.readyOps() & SelectionKey.OP_ACCEPT) ==
                SelectionKey.OP_ACCEPT) {

                // Aceita a conexão
                Socket s = serverSocket.accept();

                System.out.println( "LOG: Conexao TCP aceita de " + s.getInetAddress() + ":" + s.getPort() );

                // Make sure to make it non-blocking, so we can
                // use a selector on it.
                SocketChannel sc = s.getChannel();
                sc.configureBlocking( false );

                // Registra a conexao no seletor, apenas para leitura
                sc.register( masterSelector, SelectionKey.OP_READ );

            } else if ( key.isReadable() ) {
                SocketChannel sc = null;

                // It's incoming data on a connection, so
                // process it
                sc = (SocketChannel)key.channel();

                // Verifica se a conexão corresponde a um cliente já existente

                if((clientsMap.getClient(key)) != null){
                    boolean closedConnection = !processIncomingClientData(key);
                    if(closedConnection){
                        int id = clientsMap.getClient(key);
                        closeClient(id);
                    }
                } else {
                    boolean clientAccepted = processIncomingDataFromNewClient(key);
                    if(!clientAccepted){
                        // Se o cliente não foi aceito, sua conexão é simplesmente fechada
                        sc.socket().close();
                        sc.close();
                        key.cancel();
                    }
                }

            }
        }

        // We remove the selected keys, because we've dealt
        // with them.
        keys.clear();
    }
}

这段代码只是处理想要连接到聊天的新客户端。因此,客户端与服务器建立 TCP 连接,一旦被接受,它就会按照简单的文本协议向服务器发送数据,通知他的 id 并要求注册到服务器。我在方法 processIncomingDataFromNewClient(key) 中处理这个问题。我还在类似于哈希表的数据结构中保存了客户端及其连接的映射。我这样做是因为我需要从连接中恢复客户端 ID 和来自客户端 ID 的连接。这可以显示在:clientsMap.getClient(key) 中。但问题本身在于方法 processIncomingDataFromNewClient(key)。在那里,我只是读取客户端发送给我的数据,验证它,如果没问题,我向客户端发送一条消息,告知它已连接到聊天服务器。这是一段类似的代码:

private boolean processIncomingDataFromNewClient(SelectionKey key){
    SocketChannel sc = (SocketChannel) key.channel();
    String connectionOrigin = sc.socket().getInetAddress() + ":" + sc.socket().getPort();

    int id = 0; //id of the client

    buf.clear();
    int bytesRead = 0;
    try {
        bytesRead = sc.read(buf);
        if(bytesRead<=0){
            System.out.println("Conexão fechada pelo: " + connectionOrigin);
            return false;
        }
        System.out.println("LOG: " + bytesRead + " bytes lidos de " + connectionOrigin);

        String msg = new String(buf.array(),0,bytesRead);

        // Do validations with the client sent me here
        // gets the client id

            }catch (Exception e) {
                e.printStackTrace();
                System.out.println("LOG: Oops. Cliente não conhece o protocolo. Fechando a conexão: " + connectionOrigin);
                System.out.println("LOG: Primeiros 10 caracteres enviados pelo cliente: " + msg); 
                return false;
            }
        }

    } catch (IOException e) {
        System.out.println("LOG: Erro ao ler dados da conexao: " + connectionOrigin);
        System.out.println("LOG: "+ e.getLocalizedMessage());
        System.out.println("LOG: Fechando a conexão...");

        return false;
    }

    // If it gets to here, the protocol is ok and we can add the client
    boolean inserted = clientsMap.addClient(key, id);
    if(!inserted){
        System.out.println("LOG: Não foi possível adicionar o cliente. Ou ele já está conectado ou já têm clientes demais. Id: " + id);
        System.out.println("LOG: Fechando a conexão: " + connectionOrigin);
        return false;
    }
    System.out.println("LOG: Novo cliente conectado! Enviando mesnsagem de confirmação. Id: " + id + " Conexao: " + connectionOrigin);

    /* Here is the error */
    sendMessage(id, "Servidor pet: connection accepted");

    System.out.println("LOG: Novo cliente conectado! Id: " + id + " Conexao: " + connectionOrigin);
    return true;
}

最后,方法 sendMessage(SelectionKey key) 如下所示:

private void sendMessage(int destId, String msg) {
    Charset charset = Charset.forName("ISO-8859-1");
    CharBuffer charBuffer = CharBuffer.wrap(msg, 0, msg.length());
    ByteBuffer bf = charset.encode(charBuffer);

    //bf.flip();

    int bytesSent = 0;
    SelectionKey key = clientsMap.getClient(destId);

    SocketChannel sc = (SocketChannel) key.channel();

    try {
        /
        int total_bytes_sent = 0;
        while(total_bytes_sent < msg.length()){
            bytesSent = sc.write(bf);
            total_bytes_sent += bytesSent;

        }

        System.out.println("LOG: Bytes enviados para o cliente " + destId + ": "+ total_bytes_sent + " Tamanho da mensagem: " + msg.length());
    } catch (IOException e) {
        System.out.println("LOG: Erro ao mandar mensagem para: " + destId);
        System.out.println("LOG: " + e.getLocalizedMessage());
    }
}

因此,发生的事情是服务器在发送消息时打印如下内容:

LOG: Bytes sent to the client: 28 Size of the message: 28

因此,它告诉它发送了数据,但聊天客户端一直阻塞,在 recv() 方法中等待。因此,数据永远不会到达它。但是,当我关闭服务器应用程序时,所有数据都会出现在客户端中。我想知道为什么。

重要的是要说客户端在 C 和服务器 JAVA 中,并且我在同一台机器上运行,在 windows 下的 virtualbox 中运行 Ubuntu 来宾。我也在 windows 主机和 linuxes 主机下运行,并且不断遇到同样的奇怪问题。

我很抱歉这个问题很长,但我已经在很多地方搜索了答案,找到了很多教程和问题,包括在 StackOverflow 上,但找不到合理的解释。我真的不喜欢这个Java NIO,我也看到很多人抱怨它。我在想,如果我在 C 语言中这样做会容易得多:-D

所以,如果有人可以帮助我,甚至讨论这种行为,那就太好了!:-)

先谢谢大家了

彼得森

4

2 回答 2

1

尝试

System.out.println("LOG: " + bytesRead + " bytes lidos de " + connectionOrigin);
buf.flip();
String msg = new String(buf.array(),0,bytesRead);
于 2009-07-09T20:42:52.023 回答
-1

在接受块上,在非阻塞之后,尝试设置节点层,这样操作系统就不会等到它自己的缓冲区已满才发送数据

    socket.setTcpNoDelay(true);
于 2012-08-06T20:58:31.970 回答