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) + "| port:" + str(address)) 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))
'127.0.0.1' means local computer - so client connents with server on the same computer. Client have to use
IP from server - like
Check on server:
on Windows (in
on Linux (in console)
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.
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.