简体   繁体   中英

Java EOFException Server/Client TCP application

I am running 2 threads in my applciation. One to check for incoming packets and one to process and send packets. They both do it on the SAME STREAM.

Example for 1:

while (connection open) {
    in.readObject() instanceof ...
}

Example for 2:

while (connection open) {
    processPacket(in)
}

I'm pretty sure EOFException is when the threads try and use the stream at the same time. It's not a constant EOF but only like every 1 second I get an EOF the rest works fine. So that's why I suspect that they overlap and try to use the stream at the same time.

If that is the problem, anyone know how do I synchronize them to do it after another while still keeping the current update speed and using two threads?

I need two threads because the check for incoming waits in a line until a packet gets recived and I need the server to constantly send process and check for packets.

How do I fix the EOFException?

If your getting an EOFException, it typically means the other side hung up. You usually get these on the read side.

Here's a similar SO question

Edit 1: The question is really why is the socket closed. It can be for any number of reasons, a programmable timer on the server side checking for no data within X minutes, a firewall closing the connection, a network interruption, etc..

Both threads shouldn't be reading the same Stream.

You should read the objects and put them in a ConcurrentLinkedQueue, then from the second thread you can check the queue for objects ready to process.

EOFException is 'normal'. It happens on one thread too. Your architecture of reading in two threads simultaneously cannot possibly work, but it isn't the cause of this problem. The cause is that the peer closed the connection. This is going to happen. Unless your application protocol contains message counts or a close notify or some other means of predicting EOS, it is going to get EOFExceptions, or readLine() returning null, or read() returning -1, depending which read methods you are calling.

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