Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Socket closes before last bytes arrive to the receiver  RSS feed

 
Oleg Shubin
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm having trouble with server-client communication. In particular, the server should warn the client before closing the socket (mainly to transmit the reason for disconnect) but it seems like not all the bytes of the message arrive to the receiver.
In my connection protocol, all data is transmitted in messages that have a type and a body. Type specifies the topic of the message while the body contains data. They are sent in the following manner:
  • First byte contains the type of the message
  • The next 4 bytes form an int specifying the length of the body
  • All the next bytes are body

  • The message system has been working correctly, including the disconnect messages, until I modified the disconnect part to actually close the socket (Socket.close()) once the message has been transmitted. The current code is below:


    So, my question is: how do I send bytes and close the socket in such a way, that all the bytes arrive to the receiver before the socket closes?
    Thank you.

    P.S. I've checked similar question, and I'd like to point out that in my case the server is likely going to be working with many clients (this protocol will be used in a game engine), so I actually need to close the socket; at the same time, the server should be able to forcefully "kick" the client and still transmit the disconnect reason (e.g. the client has been banned or the server is simply shutting down) - I need the socket to be closed by the server.
     
    Henry Wong
    author
    Sheriff
    Posts: 23283
    125
    C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Oleg Shubin wrote:
    So, my question is: how do I send bytes and close the socket in such a way, that all the bytes arrive to the receiver before the socket closes?
    Thank you.


    Simply. You can't. Tail lost (of the trailing data) should not be unexpected when a socket is closed.

    You have two options. You can modify the protocol to acknowledge the close message, before you close the socket (which you don't want to do). Or you can modify the client to assume the close message, if/when they get a socket reset.

    Henry
     
    Consider Paul's rocket mass heater.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!