0

This is client.py class and This class is on mobile.

import socket c = socket.socket() c.connect(('127.0.0.1', 9998)) name = input("Enter your name : ") c.send(bytes(name, 'utf-8')) data = c.recv(1024).decode() print(data) 

This is server.py class and This class is on mac book pro.

import socket s = socket.socket() s.bind(('localhost', 9998)) s.listen(2) print('server is waiting for connections..') while True: c, addr = s.accept() name = c.recv(1024).decode() print('connected with', addr, name) st = "Hello, " + name c.send(st) c.close() 

Why am I getting "connection refused" error?

0

2 Answers 2

1

Your client and server are running on different devices. Your client is trying to connect to the local loopback IP 127.0.0.1, which will work only if the server is running on the same device as the client. That is why you are getting "connection refused" - there is no server listening locally at 127.0.0.1:9998.

If the client and server are connected to the same network (WiFi, etc), the client needs to connect to the server's actual LAN IP on that network.

If the client and server are connected to different networks (ie, they reach each other over the Internet), the client needs to connect to the public IP of the network that the server is connected to, and that network router will need to have port forwarding configured to route incoming connections to the server device.

Also, note that making the server listen on localhost does not guarantee it will be able to accept clients from other devices, depending on how localhost is implemented. It might resolve to 127.0.0.1 only. The server should instead listen on the wildcard IP 0.0.0.0 so it listens on all available network interfaces that are installed on that device. Or, it can alternatively listen on just the specific LAN IP that will actually be receiving the client connections.

Sign up to request clarification or add additional context in comments.

Comments

0

To echo what Remy just correctly said, "connection refused" is really a bit misleading. It basically means that there was no one listening at the address-and-port that the host tried to reach. It does not mean that "there was someone there, but he [actively ...] 'refused to' talk with you." "Connection failed" might have been a better term, but, here we are.

1 Comment

To be more accurate, "connection refused" generally means either 1) the OS of the device at the target IP was reached, but the OS is refusing the connection because the target port is not open OR the port's backlog is full; 2) there is a firewall/antivirus/etc blocking the connection before it can reach the target IP/port.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.