请教关于socket编程的send函数!(TCP)刚看到一篇文章是关于 socket编程在TCP的情况下,使用send函数时,阻塞与非阻塞的区别,详见下面这篇文章:
http://www.cppblog.com/artmouse/archive/2005/12/14/1762.aspx这篇文章的大意是讲:
 1 在socket阻塞时,send一定会等到将想要发送的数据copy到协议栈缓冲区为止(不管要发送的数据有多大),也就是说这个时候send返回的长度一定等于要发送的数据的长度,所以此时也不用循环send;
 2 在socket非阻塞时,send返回的长度可能小于要发送的数据的长度,所以此时用循环send;
但是我做的实验发现:
  a 不论要发送的数据要多大(我发送的数据大小是1M,发送缓冲区是8K)
  b 不论阻塞还是非阻塞
send返回的值总是等于要发送的数据的长度,也就是说一次就发送完了(或者说Copy到缓冲区了)。请问:
   i http://www.cppblog.com/artmouse/archive/2005/12/14/1762.aspx 这篇文章讲的是否对?(我认为这篇文章对)
   ii 我的实验结果怎么解释
PS:我的实验环境是win7,TCP 的server,client在同一台机器。本人第一次问问题,有没说清楚的,请见谅并提出!谢谢!

解决方案 »

  1.   


    不是么?我的理解 socket的接收缓冲区和发送缓冲区就是协议栈的缓冲区啊,不是么?
      

  2.   

    ---------------------------------
    Return Value
    If no error occurs, send returns the total number of bytes sent, which can be less than the number requested to be sent in the len parameter. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
    ------------------------------------
    Res
    If no buffer space is available within the transport system to hold the data to be transmitted, send will block unless the socket has been placed in nonblocking mode. On nonblocking stream oriented sockets, the number of bytes written can be between 1 and the requested length, depending on buffer availability on both the client and server computers.
    ---------------------------
    Notice "can be".
      

  3.   

    你说的can be 是指:
     "On nonblocking stream oriented sockets, the number of bytes written can be between 1 and the requested length, depending on buffer availability on both the client and server computers."吧?
    但我认为在我做的实验的环境中,即:非阻塞时,发送缓冲区是8k,要发送1M的数据(我还试了发送1G的数据),send不可能一次全部将数据copy至发送缓冲区吧?谢谢你的回复!
      

  4.   

    Reference to MSDN:
    Platform SDK: Windows Sockets 
    send
    The send function sends data on a connected socket.int send(
      SOCKET s,              
      const char FAR *buf,  
      int len,               
      int flags              
    );
    Parameters

    [in] Descriptor identifying a connected socket. 
    buf 
    [in] Buffer containing the data to be transmitted. 
    len 
    [in] Length of the data in buf. 
    flags 
    [in] Indicator specifying the way in which the call is made. 
    Return Values
    If no error occurs, send returns the total number of bytes sent, which can be less than the number indicated by len for nonblocking sockets. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.Error code Meaning 
    WSANOTINITIALISED A successful WSAStartup call must occur before using this function. 
    WSAENETDOWN The network subsystem has failed. 
    WSAEACCES The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST parameter to allow the use of the broadcast address. 
    WSAEINTR A blocking Windows Sockets 1.1 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. 
    WSAEFAULT The buf parameter is not completely contained in a valid part of the user address space. 
    WSAENETRESET The connection has been broken due to the keep-alive activity detecting a failure while the operation was in progress. 
    WSAENOBUFS No buffer space is available. 
    WSAENOTCONN The socket is not connected. 
    WSAENOTSOCK The descriptor is not a socket. 
    WSAEOPNOTSUPP MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only receive operations. 
    WSAESHUTDOWN The socket has been shut down; it is not possible to send on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH. 
    WSAEWOULDBLOCK The socket is ed as nonblocking and the requested operation would block. 
    WSAEMSGSIZE The socket is message oriented, and the message is larger than the maximum supported by the underlying transport. 
    WSAEHOSTUNREACH The remote host cannot be reached from this host at this time. 
    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. 
    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. 
    WSAECONNRESET The virtual circuit was reset by the remote side executing a hard or abortive close. For UPD sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a "Port Unreachable" ICMP packet. 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 system on the other end went down without notice. 
    Res
    The send function is used to write outgoing data on a connected socket. For message-oriented sockets, care must be taken not to exceed the maximum packet size of the underlying provider, which can be obtained by using getsockopt to retrieve the value of socket option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying protocol, the error WSAEMSGSIZE is returned, and no data is transmitted. The successful completion of a send does not indicate that the data was successfully delivered.If no buffer space is available within the transport system to hold the data to be transmitted, send will block unless the socket has been placed in nonblocking mode. On nonblocking stream oriented sockets, the number of bytes written can be between 1 and the requested length, depending on buffer availability on both client and server machines. The select, WSAAsyncSelect or WSAEventSelect functions can be used to determine when it is possible to send more data.Calling send with a zero len parameter is permissible and will be treated by implementations as successful. In such cases, send will return zero as a valid value. For message-oriented sockets, a zero-length transport datagram is sent.The flags parameter can be used to influence the behavior of the function 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 using the bitwise OR operator with any of the following values.Value Meaning 
    MSG_DONTROUTE Specifies that the data should not be subject to routing. A Windows Sockets service provider can choose to ignore this flag. 
    MSG_OOB Sends OOB data (stream-style socket such as SOCK_STREAM only. Also see DECnet Out-Of-band data for a discussion of this topic). 
    Notes for IrDA Sockets
    The Af_irda.h header file must be explicitly included. 
    Requirements 
      Windows NT/2000/XP: Included in Windows NT 3.1 and later.
      Windows 95/98/Me: Included in Windows 95 and later.
      Header: Declared in Winsock2.h.
      Library: Use Ws2_32.lib.See Also
    Windows Sockets Programming Considerations Overview, Socket Functions, recv, recvfrom, select, sendto, socket, WSAAsyncSelect, WSAEventSelect 
      

  5.   

    本帖最后由 wenxy1 于 2010-07-31 23:17:50 编辑
      

  6.   


    谢谢!
    照你这么说,(TCP时)send在阻塞和非阻塞下是没有区别喽?但MSDN:
    If no buffer space is available within the transport system to hold the data to be transmitted, send will block unless the socket has been placed in nonblocking mode. On nonblocking stream oriented sockets, the number of bytes written can be between 1 and the requested length, depending on buffer availability on both client and server machines.
    注意是在非阻塞的面向流的socket时,返回值才有可能小于the requested length.换句话说(我的理解),如果是阻塞的socket时只有完成copy,才会返回,所以返回值一定是the requested length。
      

  7.   


    我也认为有点讲不通,但是我看到的是这样。等我把我测试用的代码发上来,你可以试试。我怀疑:
    1 是不是因为服务器与客户端在一台机器上运行有关。
    2 win7的问题;
    当然这只是我瞎猜。
      

  8.   

    给出我写的测试代码:server端:
    #include<winsock2.h>
    #pragma comment(lib, "Ws2_32.lib")#define LISTEN_IP    "127.0.0.1"
    #define LISTEN_PORT  1207
    /// 处理与客户端通信的线程  
    DWORD WINAPI ClientThread(LPVOID lpParam)
    {
        SOCKET sock = (SOCKET)lpParam; ///得到接收缓冲区大小
    int RecLen; 
    int RecLenSize = 4; 
    getsockopt(sock,SOL_SOCKET,SO_RCVBUF,(char* )&RecLen,&RecLenSize); 
    printf("socket接收缓冲区大小为%d\n",RecLen); const int iBuflen  = 400;
        char szBuff[iBuflen+1];///接收缓冲区
        int ret = 0;
    while(1)
    {
    ///清空接收缓冲区
    memset(szBuff,0,sizeof(szBuff));
    ret = recv(sock,szBuff,iBuflen,0);//阻塞的接收 if(ret>0)
    {
    ///打印接收的收据
    printf(szBuff);

    else if(ret==SOCKET_ERROR)
    {
    int iError = WSAGetLastError();
    printf("recv返回SOCKET_ERROR WSAGetLastError == %d\n",iError);
    }
    else if(ret==0)
    {
    ///关闭 退出
    closesocket(sock);
    break;
    }

    Sleep(200);
    } return 0;
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;
    SOCKET sListen,sClient;
    HANDLE hThread;
    DWORD dwThread; wVersionRequested = MAKEWORD( 2, 2 );
    err = WSAStartup( wVersionRequested, &wsaData );//加载套接字
    if ( err != 0 ) 
    {
    return 0;
    } if ( LOBYTE( wsaData.wVersion ) != 2 ||
    HIBYTE( wsaData.wVersion ) != 2 ) 
    {
    WSACleanup( );
    return 0;
    } SOCKADDR_IN serverAddr;//获得本机的地址结构
    SOCKADDR_IN clientAddr;////定义地址族 int c_size=sizeof(SOCKADDR_IN);
    memset(&serverAddr,0,sizeof(SOCKADDR_IN)); serverAddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY); //转换Unsigned short为网络字节序的格式
    serverAddr.sin_family=AF_INET;
    serverAddr.sin_port=htons(LISTEN_PORT); sListen=socket(AF_INET,SOCK_STREAM,0);
    if(sListen == INVALID_SOCKET)
    {
    printf("创建套接字失败!\n");
    closesocket(sListen );
    WSACleanup();
    return 0; } if(bind(sListen,(SOCKADDR *)&serverAddr,sizeof(SOCKADDR))==SOCKET_ERROR)
    {
    printf("绑定套接字失败!\n");
    closesocket(sListen );
    WSACleanup();
    return 0;
    }
    if(listen(sListen,10)==SOCKET_ERROR)
    {
    printf("打开监听失败失败!\n");
    closesocket(sListen );
    WSACleanup();
    return 0;
    } while(1)
    {
    sClient=accept(sListen,(SOCKADDR *)&clientAddr,&c_size);
    if(sClient!=INVALID_SOCKET)
    {
    hThread = CreateThread(NULL,0,ClientThread,(LPVOID)sClient,0,&dwThread);
    if(hThread==NULL)
    {
    printf("Thread Creat Failed!\n");
    break;
    }
           CloseHandle(hThread);
    }

    Sleep(200);
    }
    closesocket(sListen);
    WSACleanup(); return 0;
    }Client端:(此处虽然使用的非阻塞模式,却没有使用异步I/O模型,纯粹为了测试用)
    #include <stdio.h>#include<winsock2.h>
    #pragma comment(lib, "Ws2_32.lib")#define LISTEN_IP    "127.0.0.1"
    #define LISTEN_PORT  1207int _tmain(int argc, _TCHAR* argv[])
    {
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;
    SOCKET sClient;

    wVersionRequested = MAKEWORD( 2, 2 );
    err = WSAStartup( wVersionRequested, &wsaData );//加载套接字库
    if ( err != 0 ) 
    {
    return 0;
    }

    if ( LOBYTE( wsaData.wVersion ) != 2 ||
    HIBYTE( wsaData.wVersion ) != 2 )
    {
    WSACleanup( );
    return 0;
    }

    ///server地址
    SOCKADDR_IN addrSrv;
        addrSrv.sin_addr.S_un.S_addr=inet_addr(LISTEN_IP);
        addrSrv.sin_family=AF_INET;
        addrSrv.sin_port=htons(LISTEN_PORT);

    sClient=socket(AF_INET,SOCK_STREAM,0);
    if(sClient == INVALID_SOCKET)
    {
    printf("创建套接字失败!\n");
    closesocket(sClient);
    WSACleanup();
    return 0;
    } int iErrorCode = 0;
    //向服务器发出连接请求(connect)。
    if(connect(sClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR))==SOCKET_ERROR)
    {
    iErrorCode = WSAGetLastError();
    printf("连接服务器失败!\n");

    closesocket(sClient);
    WSACleanup();
    return 0;
    } /// 待发送数据
    int len = 1024*1024;///1M
    BYTE * pbuf = new BYTE[len];
    memset(pbuf,0,sizeof(BYTE)*len); ///填充数据
    for(int i = 0;i<len;i++)
    {
    pbuf[i] = 'a' + (i%26);
    }
    ///填充数据
           
    ///发送缓冲区大小
    int SendLen; 
    int SendLenSize = 4; 
    getsockopt(sClient,SOL_SOCKET,SO_SNDBUF,(char* )&SendLen,&SendLenSize); 
    printf("socket发送缓冲区大小为%d\n",SendLen); ///修改为非阻塞模式
    int iMode = 1;
    if (ioctlsocket(sClient, FIONBIO, (u_long FAR*) &iMode)!=0) 

    printf("ioctlsocket失败!\n");
    closesocket(sClient);
    WSACleanup();
    return 0;
    }  while(1)
    {
    printf("请输入任意一个字符并回车(q退出),开始发送!!!\n");
    char c = getchar();
            getchar();///回车符
    if(c == 'q')
    break; //开始发送
    int nBytes = 0;
    int nSendBytes=0;
    while (nSendBytes < len)///发送数据
    {
    nBytes = send(sClient,(char *)pbuf+nSendBytes,len-nSendBytes,0);
    if (nBytes==SOCKET_ERROR )///出错
    {
    iErrorCode = WSAGetLastError();
    printf("send返回SOCKET_ERROR WSAGetLastError == %d\n",iErrorCode);
    }
    else///正常发送
    {
    printf("send发送了nBytes = %d\n",nBytes);
    nSendBytes = nSendBytes + nBytes;
    } Sleep(1000);
    } printf("send发送完毕!!!\n");
    } delete []pbuf; closesocket(sClient);
    WSACleanup();
    return 0;
    }
      

  9.   

    You can change the amount of Winsock kernel buffer allocated to the socket using the SO_SNDBUF option (it is 8K by default). If necessary, Winsock can buffer significantly more than the SO_SNDBUF buffer size.