Sudantha
Sudantha

Reputation: 16224

keep socket open once & send/receive message multiple times

Problem

i have a C# application which receive a stream from a socket client , after retrieving the stream i need to accept a another stream sent by the client ,

Current Code

   int length= this.DataSocket.Receive(this.buffer, this.buffer.Length, SocketFlags.None);

 // saves the first file ..... 

   length= this.DataSocket.Receive(this.buffer, this.buffer.Length, SocketFlags.None);

Details

im sure that im writing data from the socket client but after first file receive 2nd DataSocket.Receive hangs and no stream is been received.. any idea?

Upvotes: 1

Views: 1558

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064324

A network stream in isolation has no automatic segregation of messages - it is all just bytes. As such, it is necessary to split manually; the most convenient to write is using a known delimiter between records. The most convenient to read is to prefix each message with the number of bytes to read in the next message.

You need to use this information to read entire messages, otherwise the reading goes mad. In this case, I suspect you read both messages completely in the first Receive, and now there is no more data - hence the blocking (it must block until either at least one byte can be read, or it is closed).

Also - note that because you read doesn't mean you have a full message - just at least one byte. You usually need to loop to get a message.

Upvotes: 3

Related Questions