最近在網絡編程開發中遇到socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host這樣的錯誤,查了些資料也沒什么用;
最后發現原來是socket server在設計時提前將socket套接字對象關掉了,所以導致下次使用找不到socket server的套接字對象而報錯
import socket from threading import Thread import time command=["hostname","ipconfig","systeminfo"] command="###".join(command) print(command) s=socket.socket() socket.setdefaulttimeout(5) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) addr=("0.0.0.0",9999) s.bind(addr) s.listen(5) print("waiting for connecting.....") def fun(s,c,a): for i in command.split("###"): time.sleep(1) n=c.send(str(i).encode()) print "send command {} to client".format(i),n,"bytes" c.close() #s.close() while True: c,a=s.accept() if c: print("I have enter into windwos ") print a,c t=Thread(target=fun,args=(s,c,a)) t.setDaemon(True) t.start()
注釋掉s.close()就可以正常運行,多次調用了
經實驗,如果在socket server套接字對象關閉之前調用,程序是可以正常運行的,關閉之后再調用,就會報錯了!!!