简体   繁体   English

从DataInputStream读取字节数组

[英]Read byte arrays from DataInputStream

I have a TCP Client in Java which communicates with a C# TCP Server and vice versa. 我有一个Java中的TCP Client ,可以与C# TCP Server通信,反之亦然。 They communicate by sending over byte arrays. 它们通过发送byte数组进行通信。 I'm having problems with reading the byte arrays in the Client. 我在读取客户端中的字节数组时遇到问题。 The byte arrays have a fixed length of 4. 字节数组的固定长度为4。

When for example the server sends: 例如,当服务器发送:

[2, 4, 0, 2] [2,4,0,2]

[2, 4, 0, 0] [2,4,0,0]

The client output is: 客户端输出为:

Connecting to port :10000 连接端口:10000

Just connected to /192.168.1.101:10000 刚连接到/192.168.1.101:10000

Server says [2, 4, 0, 0] 服务器说[2,4,0,0]

How can I solve this? 我该如何解决? It seems like the first array gets overwritten? 似乎第一个数组被覆盖了吗?

TCPClient.java TCPClient.java

public class TCPClient {

private OutputStream outToServer=null;
private DataOutputStream out=null;
private ByteProtocol byteProtocol;
Socket client;
InputStream inFromServer;
DataInputStream in;

public void initConnection(){
     try {
        int serverPort = 10000;
        InetAddress host = InetAddress.getByName("192.168.1.101");
        System.out.println("Connecting to port :" + serverPort);
        client = new Socket(host, serverPort);
        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        outToServer = client.getOutputStream();
        out=new DataOutputStream(outToServer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void readBytes(){

    try {
        inFromServer = client.getInputStream();
        in = new DataInputStream(inFromServer);

        byte[] buffer = new byte[4];
        int read = 0;
        while ((read = in.read(buffer, 0, buffer.length)) != -1) {
            in.read(buffer);
            System.out.println("Server says " + Arrays.toString(buffer));
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

public void sendBytes(byte [] byteArray) throws IOException{
     out.write(byteArray);
}

public void closeClient() throws IOException{
    client.close();
 }
}

It looks like you are reading into the buffer twice: 您好像两次读入缓冲区:

    while ((read = in.read(buffer, 0, buffer.length)) != -1) {
        in.read(buffer);

So the contents read in the loop head are overwritten by the second read() . 因此,在循环头中读取的内容将被第二个read()覆盖。

while ((read = in.read(buffer, 0, buffer.length)) != -1) {
        in.read(buffer);
        System.out.println("Server says " + Arrays.toString(buffer));
    }

You should use DataInputStream.readFully() instead of this read() construct, see this related question . 您应该使用DataInputStream.readFully()而不是此read()构造,请参阅此相关问题 Otherwise you can't be sure you filled the buffer. 否则,您将无法确定是否已填满缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM