[英]How to disconnect client from socket server without server crshing?
我正在使用 Python 3.7 制作服务器。 它的目标是让多个人连接到它(目前是一个用于测试的客户端)并来回发送数据。 发送的数据是用户在我的游戏中的高分。 我希望服务器获取数据,将数据与最高分进行比较,然后将数据发回并让计算机将其保存到文件中。 问题是,客户端接收到的文本数据为 0 和 1: 当您退出游戏并尝试重新连接时,服务器崩溃:
BrokenPipeError:[Errno 32] 损坏 pipe
这是服务器的代码:
import socket
import sys
import time
servsock = socket.socket()
host = '192.168.158.155'
port = 5555
highest_score = '0'
servsock.bind((host, port))
print('Sucsessful bind')
servsock.listen(1)
conn, addr = servsock.accept()
print(addr, 'Has connected')
receiving = conn.recv(1024)
receiving = receiving.decode()
while True:
if receiving > highest_score:
highest_score = receiving
message = highest_score
message = message.encode()
conn.send(message)
else:
highest_score = highest_score
failed = highest_score
failed = failed.encode()
conn.send(failed)
下面是游戏客户端的代码:
# Read high score
with open('high_score/high_score.txt', 'r+') as f:
score_contents = f.read().replace("\n", " ")
f.close()
# Send data to server
lsock = socket.socket()
host = '192.168.158.155'
port = 5555
lsock.connect((host, port))
print('Connected')
ready_message = score_contents
ready_message = ready_message.encode()
lsock.send(ready_message)
print('sent')
new_high_score = lsock.recv(1024)
new_high_score = new_high_score.decode()
print(str(new_high_score))
with open('high_score/GLOBALhigh_score.txt', 'r+') as GLOBALf:
GLOBALf.truncate()
GLOBALscore_contents = GLOBALf.write(f'Highest Score:,{new_high_score}')
GLOBALf.close()
任何帮助是极大的赞赏!
你的问题的真正根源是accept
不在循环中,但这里是如何使用整数而不是字符串。 请注意,您的if
语句始终发送实际的高分,因此无需复制该代码>
import socket
import sys
import time
servsock = socket.socket()
host = 'localhost'
port = 5555
highest_score = 0
servsock.bind((host, port))
print('Sucsessful bind')
servsock.listen(1)
while True:
conn, addr = servsock.accept()
print(addr, 'Has connected')
receiving = int(conn.recv(1024))
if receiving > highest_score:
highest_score = receiving
message = str(highest_score).encode()
conn.send(message)
另一件事,当您从客户端发送分数时,您将换行符转换为空格。 不要那样做; 只需发送数字。 如果你只是要阅读,你不需要“r+”权限,如果你只是要写,你不需要“r+”权限。 为此使用“w”并跳过truncate
调用。
# Read high score
with open('high_score/high_score.txt', 'r') as f:
score_contents = f.read().strip()
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.