您的代码包含了正确的问题和答案逻辑,但是客户端和服务器之间的数据传输是脆弱的,只有在时机完美的情况下才能工作。在
我已经修改了你的代码,以帮助控制时间,并防止事情变得井然有序。我使用select()系统调用来处理超时,在客户机中,我更改了read线程,以便在服务器出现问题时通知主循环。在
这段代码离完美还有很长的路要走,但它确实可以工作,它应该帮助您构建一些最终的东西,以您喜欢的方式工作。在
NB我删除了“你现在不能加入游戏”的代码来帮助我调试原始代码,所以你可以把它放回现在。希望这对你有帮助。在
客户代码:import socket
import threading
import time
tEv = threading.Event()
tShutdown = threading.Event()
def receving(name, sock):
shutdown = False
while not shutdown:
try:
data,addr = sock.recvfrom(1024)
print(str(data))
if '?' in data:
tEv.set()
if data == "The game is finished": # message from server to stop
tShutdown.set()
shutdown = True
except:
pass
finally:
pass
#host = '192.168.26.86'
host = '127.0.0.1'
port = 0 #pick any free port currently on the computer
server = (host, 5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host,port))
s.setblocking(0)
# Start listener
rT = threading.Thread(target=receving, args=("RecvThread", s))
rT.start()
# Join the game
alias = raw_input("Name: ")
s.sendto(alias, server)
running = True
while running:
if tEv.wait(1.0):
tEv.clear()
message = raw_input(alias + ", what is your answer ? -> ")
if message != '':
s.sendto(alias + ": " + message, server)
if tShutdown.is_set():
running = False
rT.join()
s.close()
服务器代码:
^{pr2}$