Reputation: 495
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);
}
Upvotes: 1
Views: 253
Reputation: 116908
I think the right way to do this would be by using BlockingQueue
s. Instead of sending the messages in the current thread, Game
would just add them to a sendQueue
. The TCPServer
would then have a receiving thread which would add things to the readQueue
and another thread which wrote things from the sendQueue
to the socket.
I don't quite understand your thread model right now. Typically you have a thread calling accept()
on a ServerSocket
and then forking a client handler thread. If Game
is maintaining a number of these client connections then you'd have something like this:
accept()
.ClientHandler
object and adds this to the collection of clients being handled by the game.ClientHandler
has a sendQueue
and receivedQueue
-- maybe each are LinkedBlockingQueue
ClientHandler
forks a reading thread receiving from the client and adding to the receivedQueue
and a writing thread which is waiting on the sendQueue
and 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.
Upvotes: 2