我正在开发一个网络客户端程序,我用
CSocket m_Socket;
m_socket.Create(...);
m_Socket.Connect(远方IP,port);
m_Socket.Send();
m_Socket.Recv();
m_Socket.ShutDown(2);
m_Socket.Close();
为什么不能正常Close()呢?

解决方案 »

  1.   

    我能正常通讯,通讯完之后,我断开跟服务器的连接,
    我调用
    m_Socket.ShutDown(2);
    m_Socket.Close();使用sniffer抓获报文,tcp已正常发送FIN报文,并断开连接。我调用netstat 查看,却发现socket仍然存在,其处于Time_Wait状态。此时socket没有正常关闭,无法使用该端口再次创建socket,直到其超时。请教大家是否遇到过同样的问题?如何解决?
      

  2.   

    此行为是TCP协议所要求的,如果你需要快速的重用该端口,可以用SO_REUSEADDR选项:BOOL bReUseAddr = TRUE;
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&bReUseAddr, sizeof(BOOL));
      

  3.   

    这是正常情况,执行主动关闭的socket会进入TIME_WAIT状态
      

  4.   

    Time_Wait要等好几分钟,可大家平时编程正常退出后,并不要等这么久才可以重新又启动程序,一般都不要怎么等,立即就可以重新启动,而且也一般没设置SO_REUSEADDR选项,也就是一般的CLOSE(),甚至没有ShutDown()都行
      

  5.   

    不是问题:MSDN中搜索TIME_WAIT:NOTE: It is normal to have a socket in the TIME_WAIT state for a long period of time. The time is specified in RFC793 as twice the Maximum Segment Lifetime (MSL). MSL is specified to be 2 minutes. So, a socket could be in a TIME_WAIT state for as long as 4 minutes. Some systems implement different values (less than 2 minutes) for the MSL. 
    所以显示Time_Wait是正常的。你在客户端编程时没有必要定义端口,否则你需要检查其他的程序是否已经使用了此端口,如果使用还要找下一个可用端口,为什莫不让Windows自己来选择一个呢?
    CSocket::Create( UINT nSocketPort = 0, int nSocketType = SOCK_STREAM, LPCTSTR lpszSocketAddress = NULL );nSocketPort A particular port to be used with the socket, or 0 if you want MFC to select a port.
    将第一个参数设为0即可,
    不然你就判断Create 是否成功,如果失败,则换一个端口。Unix 和Windows 都支持这种方法。
    下面是socket()的说明:
    If an application does not care what local address is assigned, specify the manifest constant value ADDR_ANY for the sa_data member of the name parameter. This allows the underlying service provider to use any appropriate network address, potentially simplifying application programming in the presence of multihomed hosts (that is, hosts that have more than one network interface and address). 
      

  6.   

    thanks!已经可以了,马上给分!