0

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()

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

4 Comments

How does one do this?
I want to have a server which receives unlimited messages
@JorisFort: "How does one do this?" - I'm not sure what part of "you need ... multiple recv ... after the accept" is unclear.
I have already fixed it thanks for your reply :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.