Reputation: 1090
My TCP data is rarely, but enough for it to be noticeable, received in the wrong order, or lost entirely.
For example, my client would send Log:joehot200;Password
, and the server would receive ehot200;Password
I checked TCP - received in wrong order and TCP data occasionally received in wrong order and incomplete and neither help. They both seem to have non-answers that do not give enough detail or do not solve the problem.
I am using this code to send data on the client and the server:
public void sendData(String data){ //Server code
try{
System.out.println("Sent " + data);
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
outToClient.writeBytes(data + "\n");
}catch (Exception e){
e.printStackTrace();
}
}
public void sendData(String data){ //Client code
try{
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(data + "\n");
}catch (Exception e){
}
}
This is the sort of data that is being send/received:
Data: UID:1;Pitch:0.0
FROM SERVER: Name:1;joehot200
Data: Name:1;joehot200
FROM SERVER: Type:1;2
Data: Type:1;2
FROM SERVER: FlaBag:1;0
Data: FlaBag:1;0
FROM SERVER: Teall-104,442m:1;1
Data: Teall-104,442m:1;1
FROM SERVER: 6.572884235079,51.82797146606425,5670.44316581469,0
In fact, looking at that above data, even that is wrong!! I have no packet starting with FlaBag or Teall.
What's going wrong here?
I am sending data from multiple threads, though I am obviously receiving all the data on the same thread.
Upvotes: 0
Views: 1536
Reputation: 1502
So basically the problem is that each of your functions that calls this function:
public void sendData(String data){ //Client code
try{
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(data + "\n");
}catch (Exception e){
}
}
Calls it in a separate context, so it will create thread local DataOutputStream which will be destroyed once the thread leaves the sendData context, effectively multiple clients are sending multiple tcp packets which arrive in order, but the clients are not synchronised. To get around this issue what you should do is to declare DataOutputStream outside of your function and make the method synchronized. This will prevent multiple threads from executing the same method at the same time. In the end your code should look something like that:
public class Blaaa {
...
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
public synchronized void sendData(String data) {
outToServer.writeBytes(data + "\n");
}
}
This should take care of out of order receiving, but your threads can still invoke the sedData method out of order (though at least it will not interleave). You might need some additional logic to prevent that.
Upvotes: 1