简体   繁体   English

无法使用 TCP 套接字 pyton 在服务器上接收多条消息

[英]Cant receive multiple messages on server using TCP socket pyton

I am new to sockets and don't really know how to receiver multiple messages from the same client.我是 sockets 的新手,我真的不知道如何从同一个客户端接收多条消息。 I only receive the first message and not the rest.我只收到第一条消息,而不是 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()
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 .当前代码接受新连接,然后执行单个recv That's why it gets only the first data.这就是为什么它只获取第一个数据。 What you need are multiple recv here after the accept.你需要的是接受后这里的多个recv

... multiple messages from the same client ...来自同一客户端的多条消息

TCP has no concept of messages. TCP 没有消息的概念。 It is only a byte stream.它只是一个字节 stream。 There is no guaranteed 1:1 relation between send and recv , even if it might look like this in many situations. sendrecv之间没有保证的 1:1 关系,即使它在许多情况下可能看起来像这样。 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.因此,消息语义必须是应用程序协议的显式部分,例如用新行分隔消息,只有固定大小的消息或类似的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM