高分求救:为什么我的Socket不能关闭?

fuzb 2004-02-01 05:06:38
我正在开发一个网络客户端程序,我用
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()呢?
...全文
134 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhuyie 2004-02-02
  • 打赏
  • 举报
回复
此行为是TCP协议所要求的,如果你需要快速的重用该端口,可以用SO_REUSEADDR选项:

BOOL bReUseAddr = TRUE;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&bReUseAddr, sizeof(BOOL));
karlson0211 2004-02-02
  • 打赏
  • 举报
回复
没碰到过,mark!
zhaolaoxin 2004-02-02
  • 打赏
  • 举报
回复
gz
fuzb 2004-02-02
  • 打赏
  • 举报
回复
我能正常通讯,通讯完之后,我断开跟服务器的连接,
我调用
m_Socket.ShutDown(2);
m_Socket.Close();

使用sniffer抓获报文,tcp已正常发送FIN报文,并断开连接。

我调用netstat 查看,却发现socket仍然存在,其处于Time_Wait状态。

此时socket没有正常关闭,无法使用该端口再次创建socket,直到其超时。

请教大家是否遇到过同样的问题?如何解决?
fuzb 2004-02-02
  • 打赏
  • 举报
回复
thanks!已经可以了,马上给分!
efis 2004-02-02
  • 打赏
  • 举报
回复
不是问题:

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).
fuzb 2004-02-02
  • 打赏
  • 举报
回复
Time_Wait要等好几分钟,可大家平时编程正常退出后,并不要等这么久才可以重新又启动程序,一般都不要怎么等,立即就可以重新启动,而且也一般没设置SO_REUSEADDR选项,也就是一般的CLOSE(),甚至没有ShutDown()都行
vtable9999 2004-02-02
  • 打赏
  • 举报
回复
这是正常情况,执行主动关闭的socket会进入TIME_WAIT状态
hyamw 2004-02-01
  • 打赏
  • 举报
回复
什么错误?
yintongshun 2004-02-01
  • 打赏
  • 举报
回复
前面连接成功了吗?能正常发送数据吗?错误是什么
zhangcrony 2004-02-01
  • 打赏
  • 举报
回复
报何错误?

18,356

社区成员

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

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