我想使用socket
分别发送2条消息。到目前为止,我的代码如下。
服务器端:
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)
客户端:
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())
终端打印以下内容:
msg1 helloworld
msg2
我所期望的是单独收到的2条消息,并且这些消息的打印方式如下:
msg1 hello
msg2 world
如何更改代码以获得我想要的内容?
答案 0 :(得分:3)
您必须a)只读取您要显示的信息量,或b)在从客户端发送第二条消息之前阻止。
<强> A 强>
msg1 = conn.recv(5).decode()
print('msg1', msg1)
msg2 = conn.recv(5).decode()
print('msg2', msg2)
<强>乙强>
(服务器)
msg1 = conn.recv(128).decode()
print('msg1', msg1)
conn.send(b'Hi')
msg2 = conn.recv(128).decode()
print('msg2', msg2)
(客户端)
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())