Skip to content
Advertisement

Why can’t I send all messages with my server-client model?

I have implemented a simple server-client model to send and print messages between my Raspberry Pi and my laptop on which I run Linux, Ubuntu. Here are the client and then the server code.

import socket

ms = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ainfo = socket.getaddrinfo("ip_address_of_RaspberryPi", 1234)
#print(ainfo)
#print(ainfo[0][4])
ms.connect(ainfo[0][4])
counter = 0
while counter <= 10:
     message = input("What do you want to send? Bear in mind that you only have 11 chances!!: ")
     print(message)
     ms.send(bytes(message,'UTF-8'))
     counter += 1
ms.close()

And the server code:

import socket 

ms = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ms.bind(('',1234))
ms.listen(5)
while True:
    conn, addr = ms.accept()
    data = conn.recv(1000)
    if not data:
        break
    print(data)
conn.close()
ms.close()

I run the server code on my Raspberry Pi and the client code on my laptop. Connection happens successfully but server only prints out the first message I sent and it won’t print the other 10 messages I am trying to send. I would really appreciate any help. Thanks in advance!

Advertisement

Answer

You need to do the accept() outside of the loop:

import socket 

ms = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ms.bind(('',1234))
ms.listen(5)
conn, addr = ms.accept()
while True:
    data = conn.recv(1000)
    if not data:
        break
    print(data)
conn.close()
ms.close()

accept() waits for a new connection to be established, but you already have a connected socket. So this call will block until you establish a new connection to the server.

Advertisement