gpt4 book ai didi

python - 在 Python TCP 流中使用分隔符

转载 作者:行者123 更新时间:2023-12-04 09:34:52 25 4
gpt4 key购买 nike

我正在开发一个使用 TCP 协议(protocol)从天线收集 ADS-B 消息的程序。由于我是 Python 新手,因此我使用以下脚本建立连接。问题是我同时收到多条消息(因为 TCP 是面向流的)。例如,我想使用“\n”分隔符分隔每条消息(每条消息的开头都有“@”,结尾有“;”,长度会有所不同)。我不知道如何告诉 Python 像这样分隔每条消息,你知道吗?非常感谢
Python 版本 3.7.6,Anaconda,Windows 10

import socketserver


class MyTCPHandler(socketserver.BaseRequestHandler):
"""
# The request handler class for our server.

# It is instantiated once per connection to the server, and must
# override the handle() method to implement communication to the
# client.
# """

def handle(self):
# self.rfile is a file-like object created by the handler;
# we can now use e.g. readline() instead of raw recv() calls
self.data = self.rfile.readline().strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# Likewise, self.wfile is a file-like object used to write back
# to the client
self.wfile.write(self.data.upper())

if __name__ == "__main__":
print ("Server online")
HOST, PORT = "localhost", 10100
# Create the server, binding to localhost on port 10002
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()

import socket
import sys



def tcp_client():

HOST, PORT = "192.168.2.99", 10002
data = " ".join(sys.argv[1:])


# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:

# Connect to server and send data
sock.connect((HOST, PORT))


while True :

sock.sendall(bytes(data + "\n", "utf-8"))
# Receive data from the server
received = str(sock.recv(1024), "utf-8")


print("{}".format(received))

最佳答案

您可以尝试使用:

acumulator = ""
while True:

received = str(sock.recv(1024), "utf-8")
divided_message = received.split('\n')
if len(divided_message) >= 2:
print('One mesage: ', acumulator + divided_message[0].strip())
for i in range(1, len(divided_message) - 1):
print('One mesage: ', divided_message[i].strip())
if '\n' in divided_message[-1]:
print('One mesage: ', divided_message[-1].strip())
acumulator = ''
else:
acumulator = divided_message[-1]
else:
acumulator += divided_message[0]
如果消息由/n 分隔,您可以应用一种选择技术来划分消息,就像上面介绍的那样。如果您的消息具有固定长度,您可以只修改分隔符。

关于python - 在 Python TCP 流中使用分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62637871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com