java - Java 中的 SocketChannel 发送数据,但没有到达目标应用程序

标签 java sockets nio

为了使用 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 连接,一旦被接受,它就会按照简单的文本协议(protocol)向服务器发送数据,通知他的 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 中,我在同一台机器上运行,一个 Ubuntu Guest 在 windows 下的 virtualbox 中。我也在 windows 主机和 linuxes 主机下运行,并不断遇到同样的奇怪问题。

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

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

先谢谢大家,

彼得森

最佳答案

尝试

System.out.println("LOG: " + bytesRead + " bytes lidos de " + connectionOrigin);
buf.flip();
String msg = new String(buf.array(),0,bytesRead);

关于java - Java 中的 SocketChannel 发送数据,但没有到达目标应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1106273/

相关文章:

java - 使用java保存带有对话框的图像文件

ruby-on-rails - 将 Apache 负载均衡器代理到 Unix 套接字而不是端口

java - 使用 nio 创建文件时出现 NoSuchFileException

c# - 使用JNA将c#的字符串转换为java

java - 将注释工作的结果传递给注释方法

java - 如何存储具有相同名称但不同条目的多组数据 firestore

java - android中局域网内广播消息

java - 在 Java 中将 Meteor 中的消息服务器套接字发送到客户端

java - 收到 Netty 消息,写入对象不起作用

java - 任务完成后 SSLEngine 握手卡住了