Search code examples
pythonsocketsipadraspberry-pi

Cannot connect two devices with socket (python)


I have an Ipad and a raspberry pi. I want to broadcast a simple message from my ipad to my raspberry pi using python's library: "socket". I have a file called server.py in my raspberry pi. I have another file called client.py in my Ipad. server.py should await a connection from the Ipad, and accept it. client.py should send the broadcast message.

server.py

import socket
import threading

bind_ip = '0.0.0.0'
bind_port = 9999

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)

print("[*] Listening on {}:{}".format(bind_ip, bind_port))


def handle_client(client_socket):
    request = client_socket.recv(1024)
    print('received: {}'.format(request))
    client_socket.send(b'ACK!')
    client_socket.close()


while True:
    client, addr = server.accept()
    print("[*] Accepted connection from: {}:{}".format(addr[0], addr[1]))
    client_handler = threading.Thread(target=handle_client, args=(client,))
    client_handler.start()




client.py

import socket

HOST = "0.0.0.0"
PORT = 9999

sock = socket.socket()

print("Attempting connection... ")

sock.connect((HOST, PORT))

print("Connected")


I first ran server.py on my raspberry pi, then ran client.py on my Ipad. However, the following error message greeted me when I ran client.py:

[Errno 61] Connection refused

I made sure the server was running properly, and I checked where the client was connecting to. It should have worked.

Please help me.


Solution

  • I would like to point out that there are so many mistakes in that code. I presume that you are totally new with sockets.

    (Also try putting 'your-server's-local-ip' in the bind_ip and HOST in server.py and client.py respectively if both of your server and client are connected to the same network)

    Even though you connect with the server you'd still get greeted with another errors.

    Let me start with server.py:

    1. In server.py you are using handle_client function to recieving a message from the client while at the client end you are not sending anything.

    2. After that you're recieving the message from the client while the client is not sending anything.

    3. There is no broadcast function for sending the message to every connected client

    The main issue is that you've not learned the basics of the sockets, my only suggestion to you would be to, start things small and then increase the complexity but here, that case is totally opposite.

    You can also refer to this video to learn the basics : https://youtu.be/u4kr7EFxAKk