0

I have a TCP Client in Java which communicates with a C# TCP Server and vice versa. They communicate by sending over byte arrays. I'm having problems with reading the byte arrays in the Client. The byte arrays have a fixed length of 4.

When for example the server sends:

[2, 4, 0, 2]

[2, 4, 0, 0]

The client output is:

Connecting to port :10000

Just connected to /192.168.1.101:10000

Server says [2, 4, 0, 0]

How can I solve this? It seems like the first array gets overwritten?

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();
 }
}
Community
  • 1
  • 1
Sybren
  • 1,071
  • 3
  • 17
  • 51

2 Answers2

3

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().

Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
0
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. Otherwise you can't be sure you filled the buffer.

Community
  • 1
  • 1
user207421
  • 305,947
  • 44
  • 307
  • 483
  • so I do `in.readFully()` but what do I use instead of this line `while ((read = in.read(buffer, 0, buffer.length)) != -1) {`? – Sybren Apr 19 '15 at 12:52