. Advertisement .
..3..
. Advertisement .
..4..
Hi developer experts,
I have a small but frustrating use case, and so far, I couldn’t get my head around this problem & ideal solution. I am running my command and facing one problem with the connectionrefusederror: [errno 61] connection refused.
Below is the command I used:
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()
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))
When I run it, I get the following error:
ConnectionRefusedError: [Errno 61] Connection refused
I am looking forward to gaining some knowledge from all experts.
Thank you, guys!
The cause:
You have encountered this error because you are not using the same networks. They are different, so client cannot connect with server on the same network or computer. Therefore, the error happens.
Solution:
You have to provide your client a
IP
from server, such as192.168.0.1
.Let’s check your server:
If it’s in console on Linux:
In the case, it’s in
cmd.exe
on Windows:Ipconfig/ifconfig
returns a local IP address that is only accessible within the local network, such as192.168.0.1
. Then your router and the routers of the service provider may need external IP and setup (redirections). ExternalIP
can be the router’s or your service provider’s IP. When you access to websites like http://httpbin.org/ip , you may see your external IP address. However, it can still need more development and pose a bigger issue.Although this may not be the answer to your original question, I did encounter the error. It was because I didn’t start the server process to listen to localhost (127.0.0.1), on the port I wanted to test. To allow the client to connect on localhost, the server must be listening to localhost.