简体   繁体   中英

Reading in a Java socket from two separate classes, the newest thread is interfering with the older one

I'm pretty sure that's as titlegore as you can get, but let me try and explain: I'm trying to create a pretty simple online multiplayer game with a chatroom attached. Both the chatroom section and game section need to see the data coming from the server so they can handle data meant for them.

The two classes reading in the socket are ChatClient and Gameboard . They both implement Runnable and are running on separate threads.

Inside the run() function of each of the classes I have the following code:

try {       
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

     while (true) {

            String line = in.readLine();
            if(line != null) { ...

This works perfectly fine when only one of them exists. The second the other thread starts up only the second one actually gets any of the socket's input stream, but I'm not sure why. From my understanding of the code the two BufferedReader s should be completely independent, meaning I'm not sure why they're interfering with one another. Can I get some help?

Wrong approach: you do not use two threads to read input from the same socket. I would be rather surprised if that is at all possible.

You have one thread reading that socket, and either that thread decides where to send that data to (like in: deciding which specific sink a line should go to); or it simply copies the data and sends it to all known sinks.

From my understanding of the code the two BufferedReaders should be completely independent

Impossible. They are both reading from the same socket, which is already a problem, and they are both buffered, meaning they are liable to buffer data intended for the other thread, whatever that means. You can't do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM