ConnectionRefusedError: [WinError 10061] 无法建立连接,因为目标机器主动拒绝它错误

问题描述 投票:0回答:1

我最近正在学习一些基本的套接字编程,但是当我在服务器文件之后运行客户端时,我不断收到此错误。

[WinError 10061]无法建立连接,因为目标机器主动拒绝

这些都是使用 Python IDLE 3.6 创建的。

服务器:

import socket
import time
my_socket= socket.socket() #1
my_socket.bind(('127.0.0.1',54321))
my_socket.listen()

print("Server is listening on port 54321...")
new_socket,addr = my_socket.accept()
print('Connected to: ' + str(addr))

new_socket.sendall(b'Hello from server\n')
time.sleep(0.1) #time lag between two data
new_socket.sendall(b'on server\n')
new_socket.close()
my_socket.close()

客户:

import socket

my_socket=socket.socket()
address= '127.0.0.1'  
port=54321
my_socket.connect((address,port)) 
data=b''
while b'\n' not in data:
    data= data + my_socket.recv(1024)
print(data.decode)
my_socket.close()

即使我关闭了两个 shell 并重新启动了整个程序,此错误仍然出现。我也尝试更改端口号。

python sockets
1个回答
0
投票

我在标准机上做了一些测试,发现服务器工作正常。似乎当您进行第一次连接时,服务器会关闭,因为您的代码不包含循环并且只是顺序的。

正确的做法是:

print("Server is listening on port 54321...")
while True:
    new_socket, addr = my_socket.accept()
    print('Connected to: ' + str(addr))

    new_socket.sendall(b'Hello from server\n')
    time.sleep(0.1) # time lag between two data
    new_socket.sendall(b'on server\n')
    new_socket.close()

这样,您的服务器就不会终止,并且会根据需要接受尽可能多的请求。

同样重要的是要注意,正如您的问题中提到的,确保客户端和服务器都在同一台计算机上运行,因为您使用的是本地网络(127.0.0.1)。

© www.soinside.com 2019 - 2024. All rights reserved.