Click here to Skip to main content
15,793,452 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear friends,
I am developing a TCP socket communication program using VS. C#.
At the server side, I use one socket to accept a client. In thread function, I call Socket.Receive and on the other hand I want to send data to the client using same socket.
But when send data while receiving, an error occured. It seems to say that connection is closed forcibly by the remote host.
Please help me.
Updated 15-Jun-14 2:15am
[no name] 14-Jun-14 8:43am

1 solution

Neither the client or the server has any idea how much data is being exchanged. And, if one disconnects before the other has read the last message, the connection will be lost causing the error you are observing.

Here's a thought on what you can do:

  • Use a synchronous client/server.
  • Define a message protocol:

    • Have the client send a "GO" message like <GO/>.
    • Wait for the server to respond with an OK message like <OK/>. This indicates that the server is about to send bytes.
    • The server sends the bytes using some message like <DATA>chunk-of-data</DATA>.
    • When the client receives the bytes, the client responds an OK message (<OK/>). The server waits for the client's OK message before sending the next chunk of data.
    • When the server has send the last chunk of data and has received the client's OK message, the server sends a "finished" message like <FINISHED/>.
    • The server waits for the client to respond with <OK/>. This indicates that the server can disconnect.
    • Now you can shut down the connection on the client side.

You have very little control over the size of the buffers, so you may need to insure that two or more data buffers are properly identified in a message.

Hope that helps.

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900