I have a commandsystem to communicate between my TCP Server and Client (Java). I can send specific commands to my Client, if the Client received a command, it will execute something.
Basically, thats working. But sometimes I have to send the command + extra informations. The problem is: The informations will sometimes be sent too fast. So some information will get lost / mixed up and my Client cant execute the request properly.
The solution for me was to use Thread.sleep(), but this isn't clean nor efficent. Because there is still a risk that the information will not be received properly.
My Server:
public void sendCommand(Socket socket) throws InterruptedException, IOException {
writeMsg("CMD_POPUP", socket);
Thread.sleep(150);
writeMsg("foo", socket);
Thread.sleep(150);
writeMsg("bar", socket);
Thread.sleep(150);
writeMsg("baz", socket);
}
public void writeMsg(String message, Socket socket) throws IOException {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF(message);
}
My Client:
public void interpreteCommand(Socket socket) throws IOException {
while (true) {
switch (readMsg(socket)) {
case "CMD_POPUP":
System.out.println(readMsg(socket));
System.out.println(readMsg(socket)); //Sometimes it would be 'bar' but also sometimes it would be 'baz'
System.out.println(readMsg(socket)); //Sometimes it would be 'baz' but also sometimes it would be nothing
break;
}
}
}
public String readMsg(Socket socket) throws IOException {
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return in.readUTF();
}