VC++ socket 客户端有数据,但是服务器端recv返回是0 怎么回事

么特里亚 2013-11-13 10:17:32

用TCP调试工具显示是有数据的
...全文
507 18 打赏 收藏 转发到动态 举报
写回复
用AI写文章
18 条回复
切换为时间正序
请发表友善的回复…
发表回复
wxliangzyt 2013-11-15
  • 打赏
  • 举报
回复
开始接收正确不打印,过一段时间就会打印这个返回值为0
么特里亚 2013-11-13
  • 打赏
  • 举报
回复
引用 9 楼 bjtbjt 的回复:
应该是你在处理建立的客户端出了问题。 新的客户端必须单独另开线程。 否则accept 就已经死掉了。
我只进行了一次accept
5t4rk 2013-11-13
  • 打赏
  • 举报
回复
应该是你在处理建立的客户端出了问题。 新的客户端必须单独另开线程。 否则accept 就已经死掉了。
么特里亚 2013-11-13
  • 打赏
  • 举报
回复
引用 7 楼 zdrone 的回复:
用不着用这个循环吧?accept产生socket连接之后,就可以直接读取了,如果怕客户端数据没有发送完全的话,加个sleep然后就行了,然后通过协议包本身加长度来进行recv后的缓存拼接,while(1)这个循环1个我觉得没有任何意义,另外一个也可能导致出错。
如果不加while(1)他只能接收客户端一次发送的数据,而我需要客户端时时的数据
zdrone 2013-11-13
  • 打赏
  • 举报
回复
用不着用这个循环吧?accept产生socket连接之后,就可以直接读取了,如果怕客户端数据没有发送完全的话,加个sleep然后就行了,然后通过协议包本身加长度来进行recv后的缓存拼接,while(1)这个循环1个我觉得没有任何意义,另外一个也可能导致出错。
么特里亚 2013-11-13
  • 打赏
  • 举报
回复
引用 5 楼 yaozhiyong110 的回复:
你服务器一直打印 printf("........................\n"); ?

开始接收正确不打印,过一段时间就会打印这个返回值为0
yaozhiyong110 2013-11-13
  • 打赏
  • 举报
回复
你服务器一直打印 printf("........................\n"); ?
么特里亚 2013-11-13
  • 打赏
  • 举报
回复
引用 3 楼 yaozhiyong110 的回复:
是不是已经3秒超时了?
不会的,客户端实时在发送数据
yaozhiyong110 2013-11-13
  • 打赏
  • 举报
回复
是不是已经3秒超时了?
么特里亚 2013-11-13
  • 打赏
  • 举报
回复
这是部分代码,客户端的数据就是要处理的数据,程序开始可以接收到数据,过一段时间就会显示recv返回0,如果出现这种情况的话 怎么处理
么特里亚 2013-11-13
  • 打赏
  • 举报
回复
		SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &len);//sockConn建立连接的套接字
		if (sockConn < 0)
		{
			closesocket(sockConn);
			exit(0);
		}
	printf("socket:%d\n",sockConn);
	while(1)
	{
		unsigned char recvBuf[256] ={0};
		int j=0;
		printf("ssssssssssssssss111111111111:%d\n",sockConn);
		//接受数据
		int nNetTimeout=3000;
		int ret=setsockopt(sockConn,SOL_SOCKET, SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int));
		int length = recv( sockConn, (char*)recvBuf, 256, 0 );
		if( 0 > length)
		{
			printf("recv error:%d\n", WSAGetLastError());
			if (WSAGetLastError()==10038)
			{
				exit(0);
			}
		}
		if (0==length)
		{
			printf("........................\n");
		//	SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &len);//sockConn建立连接的套接字
		}
		printf("length = %d\n",length);
}
赵4老师 2013-11-13
  • 打赏
  • 举报
回复
仅供参考:
    SOCKET sockListen;
    sockListen=socket(AF_INET,SOCK_STREAM,0);
    //...
    // bind
    //...
ReListen:
    if (SOCKET_ERROR==listen(sockListen,1)) {
        printf("listen error!\n");
        exit(0);
    }
    SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &len);//sockConn建立连接的套接字
    if (sockConn < 0)
    {
        closesocket(sockConn);
        exit(0);
    }
    printf("socket:%d\n",sockConn);
    while(1)
    {
        unsigned char recvBuf[256] ={0};
        int j=0;
        printf("ssssssssssssssss111111111111:%d\n",sockConn);
        //接受数据
        int nNetTimeout=3000;
        int ret=setsockopt(sockConn,SOL_SOCKET, SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int));
        int length = recv( sockConn, (char*)recvBuf, 256, 0 );
        if( 0 > length)
        {
            printf("recv error:%d\n", WSAGetLastError());
            if (WSAGetLastError()==10038)
            {
                exit(0);
            }
        }
        if (0==length)
        {
            closesocket(sockConn);
            printf("Clinet Closed.\n");
            goto ReListen;
        }
        printf("length = %d\n",length);
    }
赵4老师 2013-11-13
  • 打赏
  • 举报
回复
recv The Windows Sockets recv function receives data from a connected socket. int recv ( SOCKET s, char FAR* buf, int len, int flags ); Parameters s [in] A descriptor identifying a connected socket. buf [out] A buffer for the incoming data. len [in] The length of buf. flags [in] A flag specifying the way in which the call is made. Remarks The recv function is used to read incoming data on connection-oriented sockets, or connectionless sockets. When using a connection-oriented protocol, the sockets must be connected before calling recv. When using a connectionless protocol, the sockets must be bound before calling recv. The local address of the socket must be known. For server applications, use an explicit bind function or an implicit accept or WSAAccept function. Explicit binding is discouraged for client applications. For client applications the socket can become bound implicitly to a local address using connect, WSAConnect, sendto, WSASendTo, or WSAJoinLeaf. For connected or connectionless sockets, this function restricts the addresses from which received messages are accepted. The function only returns messages from the remote address specified in the connection. Messages from other addresses are (silently) discarded For connection-oriented sockets (type SOCK_STREAM for example), calling recv will return as much information as is currently available—up to the size of the buffer supplied. If the socket has been configured for in-line reception of out-of-band data (socket option SO_OOBINLINE) and out-of-band data is yet unread, only out-of-band data will be returned. The application can use the ioctlsocket or WSAIoctl SIOCATMARK command to determine whether any more out-of-band data remains to be read. For connectionless sockets (type SOCK_DGRAM or other message-oriented sockets), data is extracted from the first enqueued datagram (message) from the destination address specified by the connect function. If the datagram or message is larger than the buffer supplied, the buffer is filled with the first part of the datagram, and recv generates the error WSAEMSGSIZE. For unreliable protocols (for example, UDP) the excess data is lost; for reliable protocols, the data is retained by the service provider until it is successfully read by calling recv with a large enough buffer. For TCP/IP, an application cannot receive from any multicast address until after becoming a group member. If no incoming data is available at the socket, the recv call blocks and waits for data to arrive according to the blocking rules defined for WSARecv with the MSG_PARTIAL flag not set unless the socket is nonblocking. In this case, a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The select, WSAAsyncSelect, or WSAEventSelect functions can be used to determine when more data arrives. If the socket is connection oriented and the remote side has shut down the connection gracefully, and all data has been received, a recv will complete immediately with zero bytes received. If the connection has been reset, a recv will fail with the error WSAECONNRESET. 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 latter is constructed by or'ing the following values: Value Meaning MSG_PEEK Peek at the incoming data. The data is copied into the buffer but is not removed from the input queue. The function then returns the number of bytes currently pending to receive. MSG_OOB Process out-of-band data. (See section DECnet Out-Of-band data for a discussion of this topic.) Return Values If no error occurs, recv returns the number of bytes received. If the connection has been gracefully closed, the return value is zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError. Error Codes WSANOTINITIALISED A successful WSAStartup must occur before using this function. WSAENETDOWN The network subsystem has failed. WSAEFAULT The buf parameter is not completely contained in a valid part of the user address space. WSAENOTCONN The socket is not connected. WSAEINTR The (blocking) call was canceled through WSACancelBlockingCall. WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. WSAENETRESET The connection has been broken due to the keep-alive activity detecting a failure while the operation was in progress. WSAENOTSOCK The descriptor is not a socket. WSAEOPNOTSUPP MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, out-of-band data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only send operations. WSAESHUTDOWN The socket has been shut down; it is not possible to recv on a socket after shutdown has been invoked with how set to SD_RECEIVE or SD_BOTH. WSAEWOULDBLOCK The socket is marked as nonblocking and the receive operation would block. WSAEMSGSIZE The message was too large to fit into the specified buffer and was truncated. WSAEINVAL The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled or (for byte stream sockets only) len was zero or negative. WSAECONNABORTED The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable. WSAETIMEDOUT The connection has been dropped because of a network failure or because the peer system failed to respond. WSAECONNRESET The virtual circuit was reset by the remote side executing a "hard" or "abortive" close. The application should close the socket as it is no longer usable. On a UDP datagram socket this error would indicate that a previous send operation resulted in an ICMP "Port Unreachable" message. QuickInfo Windows NT: Yes Windows: Yes Windows CE: Use version 1.0 and later. Header: Declared in winsock2.h. Import Library: Link with ws2_32.lib. See Also recvfrom, select, send, socket, WSAAsyncSelect, WSARecvEx
么特里亚 2013-11-13
  • 打赏
  • 举报
回复
引用 12 楼 zhao4zhong1 的回复:
用来recv的socket必须和用来accept的socket不同。
开始接收数据正常,过段时间recv就收不到收据了,是不是客户端主动断开了,如果是这种情况怎么处理
么特里亚 2013-11-13
  • 打赏
  • 举报
回复
引用 12 楼 zhao4zhong1 的回复:
用来recv的socket必须和用来accept的socket不同。
我的两个socket是分开的吧
yaozhiyong110 2013-11-13
  • 打赏
  • 举报
回复
int nNetTimeout=3000; int ret=setsockopt(sockConn,SOL_SOCKET, SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int)); 你这个去掉或者放到外面试试 本来这句就不需要每次接收都调用一次...
赵4老师 2013-11-13
  • 打赏
  • 举报
回复
用来recv的socket必须和用来accept的socket不同。
赵4老师 2013-11-13
  • 打赏
  • 举报
回复
调试Socket程序请先学会使用抓包软件比如wireshark 不知道有多少前人掉在TCP Socket send(人多)send(病少)send(财富) recv(人多病)recv(少财富) 陷阱里面啊! http://topic.csdn.net/u/20120210/09/51109ed0-07b9-41f2-b487-a51597f2ca01.html
void HexDump(char *buf,int len) {
    int i,j,k;
    char binstr[80];

    for (i=0;i<len;i++) {
        if (0==(i%16)) {
            sprintf(binstr,"%04x -",i);
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        } else if (15==(i%16)) {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
            sprintf(binstr,"%s  ",binstr);
            for (j=i-15;j<=i;j++) {
                sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
            }
            printf("%s\n",binstr);
        } else {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        }
    }
    if (0!=(i%16)) {
        k=16-(i%16);
        for (j=0;j<k;j++) {
            sprintf(binstr,"%s   ",binstr);
        }
        sprintf(binstr,"%s  ",binstr);
        k=16-k;
        for (j=i-k;j<i;j++) {
            sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
        }
        printf("%s\n",binstr);
    }
}

18,356

社区成员

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

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