python close()是假象,真正關閉Socket的方法(python中linux下close socket后連接並沒有關閉)


轉載

原文地址:https://www.cnblogs.com/semishigure/p/7428945.html

背景:

工作中自己用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)方法即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM