I am trying to establish the connection between my pc (windows11) and rpi 4 (buster v10). I have set rpi as an access point so that it has a fixed ip address, for example, 192.168.20.1 and connected my pc to it. I wrote a script to test socket communcation:
import socket, pickle, sys
class RPiClient:
def __init__(self, host, port):
self.host, self.port = host, port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self):
self.socket.connect((self.host, self.port))
def send_message(self, obj):
self.socket.sendall(pickle.dumps(obj))
def close(self):
self.socket.close()
class RPiServer:
def __init__(self, host, port):
self.host, self.port = host, port
self.socket = self.socket()
self.__data = []
self.conn, self.address = None, None
def start(self):
print(f"creating server at {self.host}:{self.port}")
self.socket.bind((self.host, self.port))
self.socket.listen()
self.conn, self.address = self.socket.accept()
def recieve_data(self):
if not self.conn or not self.address:
assert 0, f"conn: {self.conn}, address: {self.address}"
with self.conn:
while True:
data = self.conn.recv(1024)
if nto data:
break
self.__data.append(data)
return pickle.loads(b' '.join(self.__data))
def close(self):
print("Closing server")
self.socket.close()
def main():
server = RPiServer("192.168.20.1", 4160)
print("waiting for pc connection...")
try:
server.start()
except Exception as e:
print(e)
server.close()
sys.exit(1)
print("success connection")
host = server.address[0]
...
The output is as follows:
waiting for pc connection...
creating server at 192.168.20.1:4160
sever start listening for connection...
The program is stuck here due to socket.accept(). I have checked in my pc that the connection state to rpi is SYN_SENT, while rpi state is LISTENING without receiving any SYN attempt. I have also done the following steps:
- Check firewall rules
My rpi allows all connections and has no restrictions.
- Ping rpi and pc ip
I tried to ping 192.168.20.1 on my pc and also ping 192.168.20.13 (my pc ip) on rpi, both of them can ping each other successfully.
- Reboot rpi
Still do not work. I also try to connect different device to rpi, the socket connection is still failed.
It seems that the server, i.e., rpi cannot find client. Is it caused by port that I set as 4160? I use netstat -ano
to check port on my pc and only found that connections to rpi via port 22 and 445 are established.
self.socket = self.socket()
looks very wrong. There is no such method defined (presumably the secondself.
is a typo). Also, you should be using0.0.0.0
as the server'sself.host
address; this will bind to any interface with an IPv4 address and is the normal thing to do rather than hard coding a specific address. You still have to use the correct IP with the client. You can check if the server is really listening withlsof -i TCP:4160
on the Pi.