我在本地机器中使用客户端程序连接到服务器。 在网络出现故障之前,通信非常好。一旦网络离线,我正在尝试关闭套接字并重新连接。但是,shutdown(( 和 close(( 在客户端程序中没有按预期工作。到目前为止,我已经在服务器程序中看到了shutdown((和close((,而不是在任何客户端程序中。如果有任何方法可以解决问题,请帮助我。
import socket,time
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ip = '192.168.10.3'
port = 4196
address = (ip,port)
def con():
client.connect(address)
print("connected")
def comm():
while 1:
try:
client.send(b'x01x04x00x00x00x02x71xcb')
print("sent")
data= client.recv(1024)
print(" ".join("{:02x}".format(byte) for byte in (data)))
time.sleep(10)
except ConnectionResetError:
print("reset error")
client.shutdown(socket.SHUT_RD)
client.close()
time.sleep(20)
con()
con()
comm()
Error:
Traceback (most recent call last):
File "C:UsersUsereclipse-workspaceDatapwrTCP.py", line 17, in comm
datasent = client.send(b'x01x04x00x00x00x02x71xcb')
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:UsersUsereclipse-workspaceDatapwrTCP.py", line 30, in <module>
comm()
File "C:UsersUsereclipse-workspaceDatapwrTCP.py", line 26, in comm
con()
File "C:UsersUsereclipse-workspaceDatapwrTCP.py", line 11, in con
client.connect(address)
OSError: [WinError 10038] An operation was attempted on something that is not a socket
感谢您解决@KlausD。 必须创建一个新的套接字才能重新连接。 重新运行socket.socket(...(,