问题
最近用python的Socket写了一个传输通讯测试工具,但是发现在Server端调用close方法后,如果循环没有break的话,此连接还可以继续用来发送和接收数据。所以,我就觉得很是奇怪,难道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方法,可是shutdown方法是干什么的呢?
还得继续看鸟语,官方解释如下:
Shut down one or both halves of the connection. If how is SHUT_RD, further receives are disallowed. If how isSHUT_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 两个通道都关闭
也就是说,想要关闭一个连接,首先把通道全部关闭,然后在release连接,以上三个静态变量分别对应数字常量:0,1,2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17''' 使用使用shutdown来关闭socket的功能 SHUT_RDWR:关闭读写,即不可以使用send/write/recv/read SHUT_RD:关闭读,即不可以使用recv/read SHUT_WR:关闭写,即不可以使用send/write ''' import socket s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("localhost",50000)) s.sendall("this is shutdown test" + "rn") s.send("this is shutdown test") s.shutdown(socket.SHUT_RDWR) print(socket.SHUT_RDWR) print(socket.SHUT_RD) print(socket.SHUT_WR) s.close()
最后
以上就是彩色马里奥最近收集整理的关于Python中Socket的用法及Close方法假关闭Socket连接的问题问题解决方法的全部内容,更多相关Python中Socket内容请搜索靠谱客的其他文章。
发表评论 取消回复