从DataInputStream读取字节数组

时间:2015-04-19 10:40:27

标签: java tcp

我在Java中有TCP ClientC# TCP Server通信,反之亦然。它们通过发送byte数组进行通信。我在客户端读取字节数组时遇到问题。字节数组的长度固定为4.

例如服务器发送时:

  

[2,4,0,2]

     

[2,4,0,0]

客户端输出为:

  

连接到端口:10000

     

刚刚连接到/192.168.1.101:10000

     

服务器说[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();
 }
}

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

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

您应该使用DataInputStream.readFully()代替此read()构造,请参阅此related question。否则你无法确定是否填充了缓冲区。