BufferedReader无法正确读取数据

时间:2013-06-24 09:43:22

标签: java input tcp stream bufferedreader

我有一个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;
}

}

1 个答案:

答案 0 :(得分:1)

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

这里没有任何证据表明没有任何障碍。