I have a class "Server" which runs the thread "ClientHandler" that has a readline which reads from the socket. The issue is that one game starts between 2 clients I am running "GameHandler" (on the server) and I would like to use readline in this class instead. I do have a while (!game) in the clientHandler so that when game starts it stops reading from the socket, but before it manages to execute the while loop again it gets stuck in the readline as its waiting for a new message. Because of that, the next message the client sends will be read by clienthandler instead of gamehandler. Is there a way I can fix this issue?
#2 threads trying to access same bufferedreader
16 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @tranquil hinge! Please use
/closeor theClose Postbutton above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Can you show the relevant code?
but typically, you wouldn't want multiple threads to access the same BufferedReader
Instead of having two methods that deal with input why not create one method that handles reading from the socket and depending on the state of the program then calling the appropriate methods
do u mean I should get rid of the class gamehandler? or you mean i should just leave the reading be done in clienthandler?
clienthandler should do the reading. Depending if a game has started delegate the read data to the "game" method or "setup" method.
if all gamehandler does is handling the reading then yes. Otherwise refactor it.
so before the game starts, the client has to login and join a "queue" to wait for another client.
what clienthandler does is do this initial step up until game starts.
once game starts the server creates a new thread "gamehandler" with 2 clienthandlers to start the game between the 2
so it does the reading but also sets up the game
i have a while(!game){ while (readline... != null) do stuff } in clienthandler and also {while (readline ... !=null)} in gamehandler. If I do readline in clienthandler only and I would like to get a players move how would i do that?
have one thread on the sever which sole purpose is to accept clients. Wait until the second client has joined. Then put both clients in the GameHandler or in a group. This group handles reading from the sockets and sending messages to the clients as well as game logic (if needed). All setup should be done before both clients are added to the group or in the constructor of the group class. If you want to have multiple games running in parallel have a look at an ExecutorService.
would have done that but yeah I do want multiple games running in parallel
will take a look at that! thanks!
thats what the scheduled executor service is for