Flush a socket in C++

孤街浪徒 提交于 2019-12-08 04:32:09

问题


I tried to flush a socket after calling to send function in c++.
I used winsock2.h library.

I need to send the data immediatly after the send message, but I can not find any function like flash function.

I am trying to send messages to a device and it expect receiving messages one by one.
I mean that if I sending two messages in the sender like "MessageOne" and "MessageTwo", the receiver received "MessageOneMessageTwo" that is not seperate, and the device not recognize the commands.

So how can I do that?


回答1:


There is nothing you can do on the send side to make the receive side receive messages 'one by one'. Is entirely the receive side responsibility to properly reconstruct the sent frames ('messages'). Receive code must know the message length somehow (entirely protocol specific) and receive as much data as appropriate to construct an entire frame (usually achieved by posting recv with a specified length and specified that is interested only on the entire buffer, eg. MSG_WAITALL flag). I find it very hard to believe your device does not know how to handle this, and if that's indeed the case there is literally nothing you can do. I find it somehow more likely that you do not understand the device/protocol requirements and you're asking the wrong question.




回答2:


There is no "flush" functionality for sockets. If you need to send two messages in rapid succession then just send them. If it's a TCP socket then they will arrive in the correct order (the order you send them in).

This pattern is actually not uncommon; First send a message header followed by a separate send of the message data.




回答3:


The precise answer to your packet scheme question with example from Winsock FAQ




回答4:


To my knowledge there really isn't a "flush" ability. the send function returns how many bytes are sent, so you could iterate a loop until all the bytes are sent.

Edit: To add to what I've read you want from other users. The only way I know of to increase the "internal buffer" (flushing it is something winsock does on its own) is setsockopt, using the so_sendbuf option.

Article relating to it:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms740476%28v=vs.85%29.aspx




回答5:


set socket options to NDELAY on the send side



来源:https://stackoverflow.com/questions/12814835/flush-a-socket-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!