开发者

Socket.Receive - where is the end?

I want to receive data 开发者_运维百科from a client. To be precise, all data the client sends. But then I want to send some data back so I don't want to close the connection.

Maybe it's already to late in night (at least in Germany) - how can I do this? Usually I would say I'd put a semicolon or something like that in the end, but protocols like HTTP also don't do that (or do they?). How does it work there?

Thanks, eWolf


With the HTTP protocol, the Content-Length header is used to identify how much data there is in advance.

You could do something similar in your protocol.


If the other end gracefully shuts down the Socket, the Receive call will return a zero once all data has been received to indicate the end-of-stream has been reached. However, this end-of-stream condition is permanent and prevents the other end from sending any more data on the Socket.

TCP/IP is a stream protocol with no understanding of how big an logical/application-specific message is. Unless you are using the end-of-stream indication mentioned above, you need to build your own indicators into the data you send. This is sometimes referred to as "framing". For example, the sender might prefix the data with the number of bytes that follow. The receiver will first read this prefix and do a sanity check that it is a reasonable number. Then the receiver calls Receive in a loop until that many bytes have been received.

Good information on framing is available here: http://nitoprograms.blogspot.com/2009/04/message-framing.html


Look for the null terminator (0) which can be different sizes depending on the encoding of the data.

ASCII will have a 1 byte null terminator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜