Search code examples
python-3.xsocketsserverclient

Can't receive multiple messages on server using TCP socket (Python)


I am new to sockets and don't really know how to receive multiple messages from the same client. I only receive the first message and not the rest.

Server code:

import socket

IP = "127.0.0.1"
PORT = 65432

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((IP, PORT))

server.listen()

while True:
    communication_socket, address = server.accept()
    msg = communication_socket.recv(1024).decode("utf-8")
    print(msg)

Client code:

import socket
import time

HOST = "127.0.0.1"
PORT = 65432

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST, PORT))

socket.send("success".encode("utf-8"))
time.sleep(2)
socket.send("?".encode("utf-8"))
socket.close()

Solution

  • communication_socket, address = server.accept()
    msg = communication_socket.recv(1024).decode("utf-8")
    

    The current code accepts the new connection and then does a single recv. That's why it gets only the first data. What you need are multiple recv here after the accept.

    ... multiple messages from the same client

    TCP has no concept of messages. It is only a byte stream. There is no guaranteed 1:1 relation between send and recv, even if it might look like this in many situations. Thus message semantics must be an explicit part of the application protocol, like delimiting messages with new lines, having only fixed size messages or similar.