Socket server in python refuses to connect

时光怂恿深爱的人放手 提交于 2021-02-11 10:24:11

问题


I am trying to create a simple web server with python using the following code. However, When I run this code, I face this error:

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

It worths mentioning that I have already tried some solutions suggesting manipulation of proxy settings in internet options. I have run the code both in the unticked and the confirmed situation of the proxy server and yet cannot resolve the issue. Could you please guide me through this ?

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

回答1:


Standard EXAMPLE of socket connection

SERVER & CLIENT

run this in your 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()

After running this, in your IDLE execute this command and see response

>>> client(HOST,PORT,'Hello server, client sending greetings')
This is the server's hostname:  localhost
Hello server, client sending greetings
>>> 

If you try to do server with port 60000 but send message on different port, you will receive the same error as in your OP. That shows, that on that port is no server listening to connections



来源:https://stackoverflow.com/questions/54617286/socket-server-in-python-refuses-to-connect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!