python 中的套接字服务器拒绝连接

Socket server in python refuses to connect

我正在尝试使用以下代码通过 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))

套接字连接的标准示例

服务器和客户端

运行 这在你的闲置中

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 中相同的错误。这表明,在该端口上没有服务器监听连接