Python套接字:目标计算机主动拒绝连接
我试图创建一个包含计算机网络的系统,其中有一个主计算机和多个从计算机。主设备将通过套接字发送命令,从设备将响应这些命令。 我找到了一种有用的材料,它起了作用。我能够发送数据和接收答案 所以我决定为它创建一个类,使其具有服务器和客户端对象。当我创建服务器和客户机对象时,客户机对象工作正常。但是服务器对象虽然看起来正常工作,但拒绝连接Python套接字:目标计算机主动拒绝连接,python,python-sockets,Python,Python Sockets,我试图创建一个包含计算机网络的系统,其中有一个主计算机和多个从计算机。主设备将通过套接字发送命令,从设备将响应这些命令。 我找到了一种有用的材料,它起了作用。我能够发送数据和接收答案 所以我决定为它创建一个类,使其具有服务器和客户端对象。当我创建服务器和客户机对象时,客户机对象工作正常。但是服务器对象虽然看起来正常工作,但拒绝连接 ConnectionRefusedError: [WinError 10061] No connection could be made because the ta
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
这是我的班级:
import socket
from _thread import start_new_thread
class Communicator:
class Server:
def __init__(self, port, max_trans_length=128, logger=None):
self.logger = logger or getLogger("dummy")
self.port = port
self.ServerSocket = socket.socket()
self.mtl = max_trans_length
self.ThreadCount = 0
self.ServerSocket.bind((socket.gethostname(), self.port))
def threaded_client(self, connection):
connection.send(str.encode('Welcome to the Server'))
while True:
data = connection.recv(self.mtl)
reply = f"Received: {data.decode('utf-8')}"
if not data:
break
connection.sendall(str.encode(reply))
connection.close()
def listen(self):
print('Waiting for a Connection..')
self.ServerSocket.listen(5)
while True:
Client, address = self.ServerSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(self.threaded_client, (Client,))
self.ThreadCount += 1
print('Thread Number: ' + str(self.ThreadCount))
self.ServerSocket.close()
class Client:
def __init__(self, host, port, max_trans_length=128, logger=None):
self.logger = logger or getLogger("dummy")
self.host = host
self.port = port
self.mtl = max_trans_length
self.ClientSocket = socket.socket()
print('Waiting for connection')
self.ClientSocket.connect((host, port))
_ = self.ClientSocket.recv(self.mtl)
def transmit(self, data):
self.ClientSocket.send(str.encode(data))
response = self.ClientSocket.recv(self.mtl)
print(response.decode('utf-8'))
def disconnect(self):
self.ClientSocket.close()
我得到的是:
当我使用Linux机器时,我也会遇到类似的错误。因此,经过大量搜索后,我
socket.gethostname()
会限制侦听。
用黑色字符串或“127.0.0.1”对其进行更改为我解决了问题