代码改变世界

python close()是假象,真正关闭Socket的方法

2017-08-25 17:20  yongchin  阅读(17806)  评论(1编辑  收藏  举报

背景:

工作中自己用python写了一个tcp工具,然后用while循环一直接收消息,并且打印出来。然后正常close发现设备并没有离线,然后用了临时的规避方案,发现其实是一直阻塞在recv()接收方法里面,只要传输一条协议,让recv()吃到消息即可正常运行while来让其break退出,但是这种规避方式是临时的,治病要治其根,所以对现在socket进行了研究。

问题原因:

虽然已经将连接close掉了,但是client端仍然可以顺利的接收到消息,而且,如果client端发送数据的间隔小于超时时间的话,此连接可以顺利的一直使用,这样,close貌似就一点儿效果都没有了,经过在百度搜索,一直没有找到解决办法,最后还是硬着头皮去看鸟语,下面是官方解释:

close()releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, callshutdown() beforeclose().

大体意思是:close方法可以释放一个连接的资源,但是不是立即释放,如果想立即释放,那么请在close之前使用shutdown方法

解决方法

继续看鸟语,官方解释如下:

Shut down one or both halves of the connection. If how is SHUT_RD, further receives are disallowed. If how is SHUT_WR, further sends are disallowed. Ifhow is SHUT_RDWR, further sends and receives are disallowed. Depending on the platform, shutting down one half of the connection can also close the opposite half (e.g. on Mac OS X, shutdown(SHUT_WR) does not allow further reads on the other end of the connection).

大体意思是:shutdown方法是用来实现通信模式的,模式分三种,SHUT_RD 关闭接收消息通道,SHUT_WR 关闭发送消息通道,SHUT_RDWR 两个通道都关闭。

也就是说,想要关闭一个连接,首先把通道全部关闭,以上三个静态变量分别对应数字常量:0,1,2

 

通俗点说,在close()前面加上shutdown(2)方法即可

 

 

博主已搭建个人博客,更多精彩请见 《yongchin.xyz》