》》socket的recv函数问题:接收方式和flags参数

WQ771211 2010-05-03 10:36:44
recv的接口定义是:
int
WSAAPI
recv(
IN SOCKET s,
OUT char FAR * buf,
IN int len,
IN int flags
);
===========================================
问题:
1.recv阻塞线程吗,如何设置超时,超时了如何捕获异常?
2.recv中的flags是什么意思,为什么很多时候都设置为0?
3.recv在工作的时候,是要接收完len规定的字节数(或收到某结束标志,SCCKET的结束标志,不是帧结束标志)才完工吗?
比如,服务器端发送来一帧数据(假设约定数据帧不超过1024字节),调用recv一次能全部收到吗?
...全文
2367 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Eleven 2010-05-03
  • 打赏
  • 举报
回复
(1)套接字工作在非阻塞模式,设置接受超时
// 创建套接字
SOCKET sock = WSASocket(AF_INET, SOCK_STREAM, IPPOROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
if(INVALID_SOCKET == sock)
{
printf("WSASocket call failed. Error code: %d", WSAGetLastError());
}
//
int nTimeout = 5*1000;//设置超时5秒
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&nTimeout, sizeof(nTimeout));


(2)flag参数,MSDN说明:
The flags parameter can be used to influence the behavior of the function invocation beyond the options specified for the associated socket. The semantics of this function are determined by the socket options and the flags parameter. The possible value of flags parameter is constructed by using the bitwise OR operator with any of the following values.

Value Meaning
MSG_PEEK Peeks at the incoming data. The data is copied into the buffer, but is not removed from the input queue. The function subsequently returns the amount of data that can be read in a single call to the recv (or recvfrom) function, which may not be the same as the total amount of data queued on the socket. The amount of data that can actually be read in a single call to the recv (or recvfrom) function is limited to the data size written in the send or sendto function call.

MSG_OOB Processes Out Of Band (OOB) data.

MSG_WAITALL The receive request will complete only when one of the following events occurs:
The buffer supplied by the caller is completely full.
The connection has been closed.
The request has been canceled.
Note that if the underlying transport does not support MSG_WAITALL, or if the socket is in a non-blocking mode, then this call will fail with WSAEOPNOTSUPP. Also, if MSG_WAITALL is specified along with MSG_OOB, MSG_PEEK, or MSG_PARTIAL, then this call will fail with WSAEOPNOTSUPP. This flag is not supported on datagram sockets or message-oriented CO sockets.
(3)TCP是流的概念,没有边界,这个是要你自己判断的,如定义多大表示数据接受完了。一般是判断recv的返回值,这个返回值说明了实际接受的字节,它并不始终等于你recv参数中len的长度。如果没有接受完,就要继续recv。
liudafei1 2010-05-03
  • 打赏
  • 举报
回复
1.recv工作在阻塞模式
2.flag的作用查查msdn吧,比较多,比如设置超时啊,设置返回值啊。
3,recv返回一就是完成一次冲系统缓冲区到用户缓冲区的拷贝,具体有多少要看系统缓冲区现在又多少字节,第二就是超时返回。
会全部收到,系统缓冲区会为你接收保存,当然如果超过系统缓冲区长度就丢了。
尹成 2010-05-03
  • 打赏
  • 举报
回复
第一,如果你没用SELECT的话,一定有读到数据,不然不会返回,只有可能你没看到。
第二,如果有用SELECT的话。注意看你的超时结构是多少。

你可以尝试一下子,看看有不有。
int n=Recv(...);
CString str;
str.Format("收到%d个字节",n);
MessageBox(NULL,str,"fuck",MB_OK);

或者你也可以用F9,F5,F10这一系列按键来一步步调试,我想VC里面会显出来的。

18,356

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧