gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:17:00 25 4
gpt4 key购买 nike

我正在尝试使用以下代码使用 python 创建一个简单的 Web 服务器。但是,当我运行此代码时,我遇到此错误:

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

值得一提的是,我已经尝试过一些建议在互联网选项中操纵代理设置的解决方案。我已经在代理服务器未勾选和已确认的情况下运行了代码,但仍无法解决问题。你能指导我完成这个吗?

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))

最佳答案

socket连接的标准示例

服务器和客户端

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

关于python - python中的套接字服务器拒绝连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54617286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com