java - 从 DataInputStream 读取字节数组

标签 java tcp

我有一个 Java 中的 TCP 客户端,它与 C# TCP 服务器 进行通信,反之亦然。它们通过发送字节数组进行通信。我在读取客户端中的字节数组时遇到问题。字节数组的固定长度为 4。

例如,当服务器发送:

[2, 4, 0, 2]

[2, 4, 0, 0]

客户端输出是:

Connecting to port :10000

Just connected to /192.168.1.101:10000

Server says [2, 4, 0, 0]

我该如何解决这个问题?看起来第一个数组被覆盖了?

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();
 }
}

最佳答案

看起来您正在读取缓冲区两次:

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

因此循环头中读取的内容会被第二个read()覆盖。

关于java - 从 DataInputStream 读取字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29728722/

相关文章:

java - 使用 HibernateTemplate 的 findByNamedParam 函数进行分页

java - 访问另一个类中的内部枚举进行测试

在 C 中使用 TCP/IP 连接、读取、写入设备

matlab - Matlab中如何正确继承TCPIP类?

java - 如何在没有名称的情况下销毁java中的对象?

java - 使用 MapReduce 进行行计数

java - 为什么它只在90°和-90°之间旋转?

c# - 广域网通讯

c++ - 接收(recv)完整请求(例如curl HTTP)

linux - 设置 linux socket - high priority 的效果是什么?