Python ConnectionRefusedError: [Errno 61] Connection refused

耗尽温柔 提交于 2020-06-15 12:12:26

问题


Ive seen similar questions but they I couldn't fix this error. Me and my friend are making a chat program but we keep getting the error ConnectionRefusedError: [Errno 61] Connection refused We are on different networks by the way. Here is my code for the server

import socket

def socket_create():
try:

    global host
    global port
    global s
    host = ''
    port = 9999
    s = socket.socket()

except socket.error as msg:
    print("Socket creation error" + str(msg))

#Wait for client, Connect socket and port
def socket_bind():
try:
    global host
    global port
    global s
    print("Binding socket to port: " + str(port)) 
    s.bind((host, port))
    s.listen(5)
except socket.error as msg:
    print("Socket binding error" + str(msg) + "\n" + "Retrying...")
    socket_bind

#Accept connections (Establishes connection with client) socket has to       be listining
def socket_accept():
   conn, address = s.accept()
   print("Connection is established |" + " IP:" + str(address[0]) + "|    port:" + str(address[1]))
chat_send(conn)


def chat_send(conn):
 while True:
    chat =input()
    if len(str.encode(chat)) > 0:
        conn.send(str.encode(chat))
        client_response = str(conn.recv(1024), "utf-8")
    print(client_response)
def main():
socket_create()
socket_bind()
socket_accept()

main()

And my client code

import socket


#connects to server
s = socket.socket()
host = '127.0.0.1'
port = 9999
s.connect((host, port))

#gets chat
while True:
    data = s.recv(1024)
    print (data[:].decode("utf-8")) 
    chat = input()
    s.send(str.encode(chat))

回答1:


'127.0.0.1' means local computer - so client connents with server on the same computer. Client have to use IP from server - like 192.168.0.1.

Check on server:

on Windows (in cmd.exe)

ipconfig

on Linux (in console)

ifconfig

But if you are in different networks then it may not work. ipconfig/ifconfig returns local IP (like 192.168.0.1) which is visible only in local network. Then you may need external IP and setting (redirections) on your and provider routers. External IP can be IP of your router or provider router. You can see your external IP when you visit pages like this http://httpbin.org/ip . But it can still need some work nad it be bigger problem.




回答2:


This may not answer your original question, but I encountered this error and it was simply that I had not starting the server process first to listen to localhost (127.0.0.1) on the port I chose to test on. In order for the client to connect to localhost, a server must be listening on localhost.



来源:https://stackoverflow.com/questions/40814712/python-connectionrefusederror-errno-61-connection-refused

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