1

I tried sending three different messages from the server through socket and then print them in the client side. but when I do that all of the messages blending into one message. Can someone help me fix this?

Wanted output:

b'Hello1'
b'Hello2'
b'Hello3'

My current output:

b'Hello1Hello2Hello3'
b''
b''

Server code:

import socket


def main():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.bind(("127.0.0.1", 9898))
        sock.listen(1)
        client_sock, addr = sock.accept()
        hello1 = client_sock.sendall("hello1".encode())
        hello2 = client_sock.sendall("hello2".encode())
        hello3 = client_sock.sendall("hello3".encode())


if __name__ == "__main__":
    main()

Client code:

import socket


def main():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect(("127.0.0.1", 9898))
        hello1 = sock.recv(2048)
        hello2 = sock.recv(2048)
        hello3 = sock.recv(2048)
        print(hello1)
        print(hello2)
        print(hello3)


if __name__ == "__main__":
    main()
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
bob
  • 73
  • 7
  • Change `recv(2048)` to `recv(6)`. – mkrieger1 Oct 09 '22 at 21:48
  • this was just an example for a message. In reality my messages size are changing. I need a dynamic solution. – bob Oct 09 '22 at 21:49
  • 2
    How is the client supposed to know where one string ends? – mkrieger1 Oct 09 '22 at 21:50
  • I dont know thats what I am asking. I am trying to send different messages like address, email and phone number (example) and in the client I want to save them in different variables for different uses – bob Oct 09 '22 at 21:52
  • the messages just heppand to be in a row because I need them at the same time – bob Oct 09 '22 at 21:53
  • 3
    You need to design an application protocol that allows the receiver to tell where the message boundaries are. TCP doesn't do this automatically. Look at protocols like SMTP and HTTP for examples. SMTP sends commands terminated by `\r\n`, and the message body is terminated by a line containing only `.`. HTTP sends commands separated by `\r\n`, and uses `Content-Length:` header to specify the length of the body. – Barmar Oct 09 '22 at 22:03
  • 1
    You could also send JSON. – Barmar Oct 09 '22 at 22:03
  • https://stackoverflow.com/a/43420503/238704 – President James K. Polk Oct 09 '22 at 22:59

0 Answers0