简体   繁体   English

Socket.Receive-终点在哪里?

[英]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?). 通常,我会说我会在最后放置一个分号或类似的内容,但是像HTTP这样的协议也不会这样做(或者是吗?)。 How does it work there? 它在那里工作如何?

Thanks, eWolf 谢谢,eWolf

With the HTTP protocol, the Content-Length header is used to identify how much data there is in advance. 通过HTTP协议,Content-Length标头用于预先确定有多少数据。

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. 如果另一端正常关闭了Socket,则在收到所有数据以指示到达流末尾后,Receive调用将返回零。 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. TCP / IP是一种流协议,不了解特定于逻辑/应用程序的消息的大小。 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. 然后,接收方循环调用Receive,直到接收到许多字节为止。

Good information on framing is available here: http://nitoprograms.blogspot.com/2009/04/message-framing.html 有关框架的详细信息,请参见: 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. 寻找空终止符(0),根据数据的编码,其大小可以不同。

ASCII will have a 1 byte null terminator. ASCII将有一个1字节的空终止符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM