我见过类似的问题,但我无法解决此错误。我和我的 friend 正在制作一个聊天程序,但我们不断收到错误消息
ConnectionRefusedError:[Errno 61]连接被拒绝
顺便说一下,我们在不同的网络上。
这是我的服务器代码

import socket

def socket_create():
try:

    global host
    global port
    global s
    host = ''
    port = 9999
    s = socket.socket()

except socket.error as msg:
    print("Socket creation error" + str(msg))

#Wait for client, Connect socket and port
def socket_bind():
try:
    global host
    global port
    global s
    print("Binding socket to port: " + str(port))
    s.bind((host, port))
    s.listen(5)
except socket.error as msg:
    print("Socket binding error" + str(msg) + "\n" + "Retrying...")
    socket_bind

#Accept connections (Establishes connection with client) socket has to       be listining
def socket_accept():
   conn, address = s.accept()
   print("Connection is established |" + " IP:" + str(address[0]) + "|    port:" + str(address[1]))
chat_send(conn)


def chat_send(conn):
 while True:
    chat =input()
    if len(str.encode(chat)) > 0:
        conn.send(str.encode(chat))
        client_response = str(conn.recv(1024), "utf-8")
    print(client_response)
def main():
socket_create()
socket_bind()
socket_accept()

main()

还有我的客户代码
import socket


#connects to server
s = socket.socket()
host = '127.0.0.1'
port = 9999
s.connect((host, port))

#gets chat
while True:
    data = s.recv(1024)
    print (data[:].decode("utf-8"))
    chat = input()
    s.send(str.encode(chat))

最佳答案

这可能无法回答您的原始问题,但是我遇到了此错误,原因很简单,我没有首先启动服务器进程来监听我选择测试的端口上的localhost(127.0.0.1)。为了使客户端连接到本地主机,服务器必须在本地主机上监听。

关于Python ConnectionRefusedError : [Errno 61] Connection refused,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40814712/

10-10 07:18