Search code examples
raspberry-pi3

Python socket server not connecting in raspberry


I am writing a programm for chatting through python sockets. My raspberry pi (running raspbian) has the static ip 192.168.1.3 and my pc 192.168.1.4

My server.py

import socket
from threading import Thread

def send_msg(client, msg):
    client.send(bytes(msg,"utf-8"))


def listen_send(client1, address, name):
    while True:
        msg = client1.recv(1024).decode()
        if msg != '':
            for c in clients:
                if c != client1:
                    send_msg(c, "%s (%s) "%(name,address)+msg)


number = int(input("Enter number of connections"))
clients = []
addresses = []
names = []

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 25001
s.bind(('192.168.1.3', port))
print ('Socket binded to port 25001')
s.listen(number)
print('Socket is listening')

while len(clients)< number:
    cl, addr = s.accept()
    names.append(cl.recv(32).decode())
    clients.append(cl)
    addresses.append(addr[0])
    print ('Connection from ', addr[0])
    send_msg(cl, "Waiting for other connections")


for i in range(0,len(clients)):
    send_msg(clients[i], "Connection established\nYour ip is %s"%addresses[i])
    Thread(target=listen_send, args=(clients[i],addresses[i],names[i],)).start()

My client.py

import socket
from threading import Thread


def send(s):
    while True:
        msg = input()
        s.sendall(msg.encode())

def listen(s):
    while True:
        msg = s.recv(1024).decode()
        if msg != '':
            print(msg)


s = socket.socket()
port = 25001
ip = input("Enter ip\n")
s.connect((ip, port))
name = input("Enter your name\n")
s.send(bytes(name, "utf-8"))

while True:
    msg = s.recv(1024).decode()
    print(msg)
    if 'Connection established' in msg:
        break

t1 = Thread(target=send, args=(s,))
t2 = Thread(target=listen, args=(s,))
t1.start()
t2.start()

When i run the server in my pc just by changing the s.bind ip to 192.168.1.4 i can connect to my client.py from raspberry but when i run server in raspberry i cannot connect from my pc (i get TimeoutError: [WinError 10060])


Solution

  • It was a problem with firewall. Solved this with ufw allow port 25001.