【问题标题】:Errno 61: Connection refused error when trying to connect to python serverErrno 61:尝试连接到 python 服务器时连接被拒绝错误
【发布时间】:2019-07-23 17:55:18
【问题描述】:

我最近一直在尝试使用 python 的 socket 模块创建简单的在线多人游戏。我制作了服务器和客户端程序的初稿,虽然当我在同一台计算机上运行它们时它们运行良好,但我在另一台计算机上运行时尝试连接客户端会导致以下错误消息:

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))

我一直在使用最新版本的 raspbian 从 raspberry pi 3 型号 b 运行服务器,并且失败的客户端测试已在各种 mac 上运行。

【问题讨论】:

    标签: python sockets


    【解决方案1】:

    虽然当我在同一台计算机上运行它们时它们运行良好,但我在另一台计算机上运行时尝试连接客户端会导致以下错误......

    在客户端,你仍然有host = '127.0.0.1'(即localhost),但是如果你想连接到服务器另一台计算机上,你必须设置@ 987654322@ 到该计算机的地址。在服务器中,您应该将host = '127.0.0.1' 更改为host = '0.0.0.0'

    【讨论】:

    • 谢谢。我会试试的。但是,现在编程到服务器和客户端的 ip 地址是服务器的地址。
    • 有点遗憾的是,您没有现在显示代码。
    • 建议失败,所以代码还是一样。
    猜你喜欢
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2014-09-28
    • 1970-01-01
    • 2013-02-24
    • 2014-06-18
    相关资源
    最近更新 更多