我最近一直在尝试使用python的套接字模块创建简单的在线多人游戏。我制作了服务器和客户端程序的初稿,尽管当我在同一台计算机上运行它们时,它们都能正常工作,但是当我尝试在另一台计算机上运行时连接客户端时,会出现以下错误消息:
Traceback (most recent call last):
File "/Users/Admins2-Admins_In_Space/Downloads/gameclient.py", line 22, in <module>
client.connect((host,port))
ConnectionRefusedError: [Errno 61] Connection refused
(两台计算机都连接到同一路由器,因此这不是问题。)服务器代码是
import socket, threading
class dataBase():
"A class to store all playerdata"
def __init__(self):
self.data = []
class client():
"handles an individual client"
def __init__(self,ip,port,value,dataBase):
self.mainThread = threading.Thread(None,self.run)
self.ip = ip
self.port = port
self.value = value
self.dataBase = dataBase
print('New connection with' + ip)
self.mainThread.start()
def run(self):
while True:
data = conn.recv(1024).decode()
if data != None:
exec('data = ' + data)
self.dataBase[self.value] = data
data = self.dataBase
message = []
for d in range(len(data)):
if d == value:
continue
message.append(data[d])
if message != []:
conn.send(str(message).encode())
else:
self.conn.close()
break
if __name__ == '__main__':
data = []
host = '127.0.0.1'
port = 1234
value = 0
threads = []
sock = socket.socket()
sock.bind((host,port))
while True:
sock.listen(5)
(conn,(ip,port)) = sock.accept()
newThread = client(ip,port,value,data)
data.append(())
threads.append(newThread)
value += 1
for t in threads:
t.join()
这是客户,直到第22行
import pygame, socket, sys
from pygame.locals import *
host = '127.0.0.1'
port = 1234
up = False
down = False
left = False
right = False
x = 0
y = 0
data = None
if __name__ == '__main__':
pygame.init()
window = pygame.display.set_mode((1250,1000), 0, 32)
pygame.display.set_caption('client test')
client = socket.socket()
client.connect((host,port))
我一直在使用树莓派pi 3模型b和最新版本的raspbian运行服务器,并且失败的客户端测试已在各种Mac上运行。
答案 0 :(得分:0)
尽管当我在同一台计算机上同时运行它们时,它们可以完美工作,但是当我尝试在另一台计算机上运行客户端时,尝试连接客户端会导致以下错误……
在客户端中,您仍然有host = '127.0.0.1'
(即 localhost ),但是如果要连接到另一台计算机上的服务器 ,则必须将host
设置为该计算机的地址。在服务器中,您应该将host = '127.0.0.1'
更改为host = '0.0.0.0'
。