先上代碼
服務端代碼
import socket
def start_server():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 6666
address = (host, port)
s.bind(address)
s.listen(3)
conn, temp = s.accept()
conn.send("welcome to my server")
#問題在這裡,如果客戶端沒有recv上邊服務器發送的welcome to my server,再調用recv就會出錯
msg = conn.recv(1024)
print "msg = ", msg
conn.close()
s.close()
if __name__ == "__main__":
start_server()
服務端代碼非常簡單
然後上客戶端代碼(先上沒問題的)
import socket
def start_client():
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 6666
address = (host, port)
conn.connect(address)
print "-----------"
print conn.recv(1024) #############注釋error#######
conn.close()
if __name__ == "__main__":
start_client()
這樣子先開服務端,再開客戶端是沒問題的。
這時問題來了。如果我把客戶端的conn.recv(1024)注釋掉,當客戶端代碼跑完,服務端就會有問題了。
服務端出錯提示如下:
Traceback (most recent call last):
File "C:\Program Files (x86)\Adobe\Adobe Flash Builder 4.7\eclipse\dropins\pydev\plugins\org.python.pydev.debug_2.5.0.2012040618\pysrc\pydevd.py", line 1346, in
debugger.run(setup['file'], None, None)
File "C:\Program Files (x86)\Adobe\Adobe Flash Builder 4.7\eclipse\dropins\pydev\plugins\org.python.pydev.debug_2.5.0.2012040618\pysrc\pydevd.py", line 1060, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "E:\pythonCode\server.py", line 31, in
start_server()
File "E:\pythonCode\server.py", line 24, in start_server
msg = conn.recv(1024)
socket.error: [Errno 10053]
是什麼問題呢?
我想了很久,也試過好多測試代碼,發覺如果建立連接後,在一端A,先發送一些數據,如果B端沒有recv,且當B端連接close的時候。A端因為阻塞在recv部分的代碼不是如約的得到空字符串,而是出現了這個報錯。我的問題是python寫socket編程必須send,recv一一對應使用麼???
剛開始學,各位大牛指導下啊
這是網絡通信中的一個錯誤處理而已。需要你服務器端對它進行處理就可以了
http://blog.csdn.net/tw7613781/article/details/7395190