我在Pygame中创建一个游戏,需要多人游戏的客户端 - 服务器部分。
首先,我正在检查是否有少于两个连接。如果是这种情况,客户端将显示一个屏幕,显示“等待连接”。
我让客户成功发送了一个' 1'发送给服务器的消息,该消息将以' 1'如果服务器未满。因此,如果服务器没有响应1,则服务器已满,客户端可以继续。
但是,我收到了标题中提到的错误。
服务器代码:
import socket
import sys
import threading
from _thread import *
import time
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=socket.gethostname()
ip=socket.gethostbyname(host)
port=8000
connections=[]
print('Your local ip address is',ip)
s.bind((host,port))
s.listen(2)
def threaded_client(connection):
while True:
data=connection.recv(2048) #anything we receive
if not data:
break
connection.close()
def checkconnected(connections):
noofconn=len(connections)
while True:
print('Waiting for a connection...')
connection,address=s.accept()
print(address,'has connected to server hosted at port',address[1])
connections.append(address)
data=connection.recv(1024)
received=[]
counter=0
for letter in data:
received.append(data[counter])
counter+=1
received=(chr(received[0]))
if received=='1':#handling initial connections
if len(connections)!=2:
s.sendall(b'1')
if not data:
break
start_new_thread(threaded_client,(connection,))
s.close()
调用它的客户端代码:
host=socket.gethostname()
ip=socket.gethostbyname(host)
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
address=address
port=8000
if address==ip:
ishost=True
else:
ishost=False
try:
s.connect((address,port))
connectionwaitingmenu()
connected=False
while connected==False:
s.sendall(b'1')
data=s.recv(1024)
received=[]
counter=0
for letter in data:
received.append(data[counter])
counter+=1
received=(chr(received[0]))
if received=='1':
connected=False
elif received!='1':
connected=True
classselection()
错误发生在服务器代码中的s.sendall(b' 1')行。
答案 0 :(得分:3)
您的代码中还有一些其他问题,但标题中的错误原因是您使用了错误的套接字在服务器端发送和接收数据。
当服务器接受新客户端(conn, addr = server.accept()
)时,它将返回新套接字,它代表您与客户端通信的通道。通过conn
上的阅读和书写,与该客户的所有进一步沟通都会发生。您不应该在recv()
上调用sendall()
或s
,这是服务器套接字。
代码看起来像这样:
# Assuming server is a bound/listening socket
conn, addr = server.accept()
# Send to client
conn.sendall(b'hello client')
# Receive from client
response = conn.recv(1024)
# NO
server.send(b'I am not connected')
this_wont_work = server.recv(1024)