I have a class Game that uses a class TCPServer. I would like to seperate all the low level sending and receiving in TCPServer. So I give TCPServer a separate thread that constantly reads incoming messages. I would like to return these messages to Game. But I dont know how to do this. Game should also react on these messages bij responding by sending a message to the clients.
I think/know it is possible by moving the thread from TCPServer to Game but is this the best way to solve this? Isn’t it better to keep the 2 classes separate.
I have the following pseudocode.
public class Game{
TCPServer tcpServer = new TCPServer();
public void execute(){
// do something
Object o = new Object;
send(o);
if(receive(o)){ // WRONG
// do something with the receive object
}
}
private void send(Object o){
tcpServer.send(o);
}
private Object receive(Object o){
return tcpServer.receive(o);
}
public class TCPServer extends Thread{
private ServerSocket serverSocket;
Socket client = new Socket;
public void run(){
Object o = receive();
// How do I get this object o in the Server class in function execute()?
}
private Object receive(){
return serverSocket.listen();
}
public void send(Object o){
client.send(o);
}
I think the right way to do this would be by using
BlockingQueues. Instead of sending the messages in the current thread,Gamewould just add them to asendQueue. TheTCPServerwould then have a receiving thread which would add things to thereadQueueand another thread which wrote things from thesendQueueto the socket.I don’t quite understand your thread model right now. Typically you have a thread calling
accept()on aServerSocketand then forking a client handler thread. IfGameis maintaining a number of these client connections then you’d have something like this:accept().ClientHandlerobject and adds this to the collection of clients being handled by the game.ClientHandlerhas asendQueueandreceivedQueue— maybe each areLinkedBlockingQueueClientHandlerforks a reading thread receiving from the client and adding to thereceivedQueueand a writing thread which is waiting on thesendQueueand writes to the client socket.There’s a lot of work here to get this right. How to properly shutdown both reader and writer threads when the client socket closes is going to be a challenge.
Hope something here helps.