Java ObjectOutputStream on Socket not flush () ing

I am working on a network application written in Java using ObjectOutputStream and ObjectInputStream on top of Sockets for messaging. My code is as follows:

Sender:

ObjectOutputStream out; ObjectInputStream in; try{ Socket socket=new Socket(address, port); socket.setSoLinger(true, socketLingerTime); out=new ObjectOutputStream(socket.getOutputStream()); out.writeObject(message); out.flush(); out.close(); }catch (variousExceptions)... 

Recipient:

 Object incoming; try{ incoming=myObjectInputStream.readObject(); }catch (SocketException socketError) { if (socketError.getMessage().equals("Connection reset")) { //this is the exception I get } } 

Sometimes the message goes through ok, but sometimes I get a thrown exception instead of an object. Shouldn't a flash push a message to the other side? Am I somehow using this function incorrectly? Or is it some kind of bug in the Java / OS core network code?

Thanks!

UPDATE:

I have tracked this several times already, and it seems that this happens only when system resources are credited to something. I could not reproduce it outside of VirtualBox, but it could be just because VirtualBox does not have many resources to start with. I will keep this question up to date as I study it further.

+4
source share
5 answers

It turns out the problem was caused by the Nagle algorithm; the output buffer is in the OS, so it was not affected by the flash. The solution is to disable the Nagle algorithm with Socket.setTcpNoDelay (true) and buffer messages at the user level using BufferedOutputStream.

+6
source

In my case, this is a stupid problem, but I'm tired of 4 hours. Just use outStream.writeln ("); or outStream.write (mess +" \ n "); Because reader.readLine () reads until it finds the character '\ n' . So write () will not work on its own.

+1
source

You should be able to send one object per connection.

To ensure that resources are cleaned in order, it is best to close the socket as well as the output stream.

close () will cause a reset, so it should be redundant.

What happens if you do not install SO Linger?

What actual exception do you get?

0
source

It seems that the firewall in one of the routers on the way from the client to the server for some reason sends RST. I do not believe that something is wrong with your code. I tried to reproduce the problem but could not.

0
source

Resetting connections can be caused by writing to a connection that is already closed at the other end. Detection can occur at the next I / O or at the next, for example, read. In other words, this may be caused by an error in your application protocol. SO_LINGER will not help, do not mess with this.

0
source

Source: https://habr.com/ru/post/1337494/


All Articles