我正在尝试使用以下代码用 Python 创建一个简单的 Web 服务器。但是,当我运行此代码时,我遇到此错误:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
值得一提的是,我已经尝试了一些建议在 Internet 选项中操纵代理设置的解决方案。我在代理服务器未勾选和已确认的情况下都运行了代码,但仍然无法解决问题。您能指导我吗?
import sys import socketserver import socket hostname = socket.gethostname() print("This is the host name: " + hostname) port_number = 60000 soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((hostname,port_number))
服务器和客户端
在 IDLE 中运行它
import time import socket import threading HOST = 'localhost' # Standard loopback interface address (localhost) PORT = 60000 # Port to listen on (non-privileged ports are > 1023) def server(HOST,PORT): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) while True: conn, addr = s.accept() data = conn.recv(1024) if data: print(data) data = None time.sleep(1) print('Listening...') def client(HOST,PORT,message): print("This is the server's hostname: " + HOST) soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((HOST,PORT)) soc.send(message) soc.close() th=threading.Thread(target = server,args = (HOST,PORT)) th.daemon = True th.start()
运行此命令后,在 IDLE 中执行此命令并查看响应
>>> client(HOST,PORT,'Hello server, client sending greetings') This is the server's hostname: localhost Hello server, client sending greetings >>>
如果你尝试使用端口 60000 来做服务器,但发送消息到不同的端口,你会收到和你的 OP 中一样的错误。这表明,该端口上没有服务器在监听连接