我正在尝试使用以下代码使用python创建一个简单的Web服务器。 但是,当我运行此代码时,会遇到此错误:
ConnectionRefusedError:[WinError 10061]无法建立连接 因为目标机器主动拒绝了它
值得一提的是,我已经尝试了一些建议在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))
答案 0 :(得分:0)
套接字连接的标准示例
服务器和客户端
在您的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中相同的错误。这表明,该端口上没有服务器在监听连接