不从输入流中读取 RUDP 数据包

RUDP Packets are not read from inputstream

我正在使用 RUDP 协议发送和接收数据包,使用 this 非常有用的 java 库实现了 java 中的 RUDP 协议。该库的设计与 TCP 非常相似。它比较使用ReliableServerSocket作为ServerSocket和ReliableSocket作为Socket。

然而,当我创建到服务器的客户端连接时,我确实偶然发现了一个错误。服务器和客户端之间的连接已成功创建,因为执行了 accept() 方法之后的所有内容。但是,当尝试从中读取时,输入流不包含任何字节。

客户:

public class Client {

ReliableSocket rs;

public Client() throws IOException {
    rs = new ReliableSocket();
    rs.connect(new InetSocketAddress("127.0.0.1", 3033));
    
    String message = "Hello";
    
    byte[] sendData = message.getBytes();

    OutputStream os = rs.getOutputStream();

    os.write(sendData, 0, sendData.length);
    
}

public static void main(String[] args) throws IOException {
    new Client();
}

}

服务器:

public class Server {

ReliableServerSocket rss;
ReliableSocket rs;

public Server() throws Exception {
    rss = new ReliableServerSocket(3033);
    
    while (true) {
        rs = (ReliableSocket) rss.accept();
        
        System.out.println("Client connected");

        byte[] buffer = new byte[100];
        
        InputStream in = rs.getInputStream();
        
        in.read(buffer);
        
        //here the value doesn't return from the inputstream
        System.out.println("message from client: " + new String(buffer).trim());

    }
}

public static void main(String[] args) throws Exception {
    new Server();
}

}

该代码不起作用,因为它假定写入已发送字节,但是根据 Javadoc for OutputStream

Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

因此将此添加到客户端将确保发送内容。

  os.flush();

事实证明,RUDP 库就是这种情况 - 假设这是 ReliableSocketOutputStream 的实际源代码,第 109 行是 class 中唯一底层套接字实际上是写入即 flush().

在服务器端 - 它应该循环运行直到连接关闭。看 Javadoc for InputStream

Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

因此,如果它返回并且没有任何数据,那是因为其他原因(文件末尾是关闭的同义词 stream/socket)。