Reputation:
I want to send 2 messages separately using socket
. My code so far is below.
Server end:
from socket import *
s = socket(AF_INET, SOCK_STREAM)
s.bind(('localhost', 8888))
s.listen(1)
conn, addr = s.accept()
msg1 = conn.recv(128).decode()
print('msg1', msg1)
msg2 = conn.recv(128).decode()
print('msg2', msg2)
Client end:
from socket import *
sock = socket(AF_INET, SOCK_STREAM)
sock.connect(('localhost', 8888))
msg1 = "hello"
sock.sendall(msg1.encode())
msg2 = "world"
sock.sendall(msg2.encode())
The terminal prints the following:
msg1 helloworld
msg2
What I expected was 2 messages received separately, and for them to be printed like this:
msg1 hello
msg2 world
How can I change my code to get what I want?
Upvotes: 3
Views: 1225
Reputation: 51787
You have to either a) only read the amount of information you want to display, or b) block before sending the second message from the client.
A
msg1 = conn.recv(5).decode()
print('msg1', msg1)
msg2 = conn.recv(5).decode()
print('msg2', msg2)
B
(server)
msg1 = conn.recv(128).decode()
print('msg1', msg1)
conn.send(b'Hi')
msg2 = conn.recv(128).decode()
print('msg2', msg2)
(client)
msg1 = "hello"
sock.sendall(msg1.encode())
sock.recv(2048) # but we don't really care what the message is
msg2 = "world"
sock.sendall(msg2.encode())
Upvotes: 5