简体   繁体   English

c select()读取直到空字符

[英]c select() reading until null character

I am implementing a proxy in c and am using select() to not block on I/O. 我正在c中实现代理,并且正在使用select()来不阻止I / O。 There are multiple clients connecting to the proxy, so I include the socket descriptor # in my messages so that I know to which socket to forward a reply message from the server. 有多个客户端连接到代理,因此我在消息中包含套接字描述符#,以便知道从服务器将答复消息转发到哪个套接字。

However, sometimes read() will not receive the full message up to the null character, but will send the rest of the message on the next round of select(). 但是,有时read()不会收到完整的消息,直到空字符为止,而是在下一轮select()上发送其余消息。 I would like to receive the full message at once so that I will know which socket to forward the reply to (buffering will not work, since I don't know which message belongs to which when there are multiple clients). 我想立即收到完整的消息,以便知道转发答复的套接字(缓冲将不起作用,因为当有多个客户端时,我不知道哪个消息属于哪个消息)。 Is there a way to do this without blocking on read while waiting for a null character to arrive? 有没有办法在等待空字符到达时不阻塞读取?

There is no such thing as a message in TCP. TCP中没有消息。 It is a byte stream protocol. 这是一个字节流协议。 You write bytes, it sends bytes, you read bytes. 你写字节,它发送字节,你读字节。 There is no guarantee how many bytes you will receive at any one time and there is no guaranteed association between the amount of data written by a single write and read by a single read. 无法保证您一次可以接收多少字节,也不能保证单次写入和单次读取所读取的数据量之间存在关联。 If you want messages you must implement them yourself. 如果需要消息,则必须自己实现。 Any given read may read zero, one, or more bytes, up to the length of the buffer. 任何给定的读取都可以读取零,一个或多个字节,直到缓冲区的长度。 It might be half a message. 可能只有一半信息。 It might be one and a half messages. 可能是一条消息。 What it is is entirely up to you. 这完全取决于您。

Use ZeroMQ if you're doing individual messages. 如果要处理单个消息,请使用ZeroMQ。 It has bindings for a huge number of languages and is a great abstraction for networking. 它具有对多种语言的绑定,是网络的绝佳抽象。 In fact, it can handle this proxy model for you. 实际上,它可以为您处理此代理模型。

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

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