-1

我有一个 TCP 服务器客户端对。客户端有一个线程用于处理来自服务器的数据。问题是,在从服务器接收到第一个数据之前,缓冲读取器被阻塞。但是一旦收到第一个数据,它就会在有用的数据之间不断发送 0。有谁知道为什么?以及如何解决这个问题?

    connection = new Socket(ip, port);
    output = new DataOutputStream(connection.getOutputStream());
    input = new BufferedReader(new InputStreamReader(connection.getInputStream()));

并且这部分被修改以处理 0,但这并不理想:

 try {
                opcode = (char) input.read();
            } catch (IOException ex) {
                ErrorFrame erfframe = new ErrorFrame("De verbinding is verbroken voordat we de opcode van het packet konden lezen", "Herverbinden", IRIGui.ConnectionType);
            }
            System.out.println("Data received!!" + opcode);
            int opcodenr = Character.getNumericValue(opcode);
            char sensortype = '0';
            try {
                do {
                    sensortype = (char) input.read();
                } while (sensortype == 0);

            } catch (IOException ex) {
                ErrorFrame erfframe = new ErrorFrame("De verbinding is verbroken voordat we de sensortype van het packet konden lezen", "Herverbinden", IRIGui.ConnectionType);
            }

服务器代码:

public static void main(String argv[]) throws Exception { ServerSocket welcomeSocket = new ServerSocket(25566);

while (true) {
    Socket connectionSocket = welcomeSocket.accept();
    BufferedReader inFromClient =
            new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
    DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
    int request = inFromClient.read();
    System.out.println("erjioejfioe " + request);
    if (request == 4) {
        outToClient.writeBytes("41");
        outToClient.write(5);
        outToClient.writeInt(5);
        outToClient.writeInt(3);
        outToClient.writeInt(6);
        outToClient.writeInt(5);
        outToClient.writeInt(1);
    }
    request = 0;
    request = inFromClient.read();
    System.out.println("erjioejfioe " + request);
    if (request == 4) {
        System.out.println("SENDING THE SHIT");
        outToClient.writeBytes("41");
        outToClient.write(5);
        outToClient.writeInt(3);
        outToClient.writeInt(7);
        outToClient.writeInt(2);
        outToClient.writeInt(4);
        outToClient.writeInt(3);
        System.out.println("We get here!!");
    }
    break;
}

}

4

1 回答 1

1

您正在编写 32 位的整数,并且在您的情况下都具有三个前导零字节,并且正在读取 16 位的字符,因此您读取的每个奇数字符都包含两个零字节。这没有任何意义。如果你用 写writeInt(),用 读readInt()。所有其他DataInput/OutputStream方法也是如此。对称地使用它们。

这里没有任何证据表明没有任何阻塞。

于 2013-06-24T12:48:48.283 回答