我正在尝试制作2人在线局域网游戏。我已经创建了服务器和客户端,它们可以连接。问题在于,当2个客户端尝试发送信息时,服务器无法正确处理来自两个客户端的信息,但是当仅连接一个客户端时,服务器将正确处理信息。 这是服务器代码:
import socket
import os
numOfClients = 0
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('192.168.88.1', 10000))
serversocket.listen(5)
while numOfClients != 2:
if numOfClients == 0:
c, a = serversocket.accept()
elif numOfClients == 1:
c1, a1 = serversocket.accept()
if numOfClients == 0:
print(a, 'has connected!')
elif numOfClients == 1:
print(a1, 'has connected!')
numOfClients += 1
print('Connected to ', a)
print("2 Players have connected!")
while True:
msg1 = c.recv(1024)
if msg1 != b'':
print(msg1, '1')
msg2 = c1.recv(1024)
if msg2 != b'':
print(msg2, '2')
这是您真正需要的所有客户端代码:
# Socket Stuff
port = 10000
host = '192.168.88.1'
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = host, port
socket.connect(server)
socketMsg = b''
# Main Game loop
while True:
# Calls Functions
socket.send(socketMsg)
# socketMsg is assigned above, it is assigned to b'Works!' just so that I can see if it actually works
socketMsg = b''
redrawWin()
get_events()
如果我在这篇文章中做错了什么,对不起,这是我第二篇文章堆积
答案 0 :(得分:0)
您的第一个套接字连接阻止了以后的连接。有多种解决方案。
select
模块旨在管理此问题。