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