I have 2 classes where I have one to send commands to a socket, another which receives (and sometimes answers commands) .
Do I have to synchronize this? Or is this not necessary?
Both classes run in their own threads with the socket object passed down to each of them as argument upon thread.start();
Is this the proper way to do it or could I do something more efficient?
Would this have chances of causing errors?
The sending part:
public void run(){
send_chatline("roomf");
int vvv = 0;
while (this.socket.isConnected()){
try{
Thread.sleep(10000);
vvv++;
Thread.sleep(10000);
send_chatline("alive");
Thread.sleep(10000);
if (vvv == 1) {
this.socket.flush();
this.socket.send("T,-1," + this.playerid * 3);
this.socket.flush();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
But remember! The recieveFromSock class also writes sometimes when specific commands appear.
The only function of sendTosock is to keep the connection alive (being able to remain online).
The only guarantee you have is that a byte sent, is sent once, and that a byte read is read once. Others may say that the synchronization is taken care of by the runtime-library, or the underlying operating system. Any such statement is runtime-implementation dependent and/or operating system dependent (and should in my opinion be disregarded from).
So, if you have one thread reading from the socket, and one thread writing to the socket, you should be fine without synchronization.
If more than one thread may write to the socket, you should synchronize their actions to make sure the output sent from the two threads doesn’t get interleaved.
Same applies if two threads read from the socket. You should synchronize the reads to make sure that data read by one thread doesn’t have “gaps” due to reads of another thread.
Similar question, same conclusion: