在 Python TCP 流中使用分隔符 [英] Using delimiters in a Python TCP stream

查看:38
本文介绍了在 Python TCP 流中使用分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a program using TCP protocol to collect ADS-B messages from an antenna. Since I am new to Python, I used the following scripts to establish connection. The problem is that I receive several messages at the same time (since TCP is stream-oriented). I would like to separate each message using a "\n" delimiter for instance (each message has "@" at the beginning and ";" at the end and the length varies). I have no idea of how to tell Python to separate each message like this, do you have any idea ? Thanks a lot

Python 3.7.6 版,Anaconda,Windows 10

Python version 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 分隔,您可以应用选择技术来分割消息,就像上面介绍的那样.如果您的消息有固定长度,您可以修改分隔符.

If the message is separated by /n you can divide the message applying a selection technique, like the one presented above. If your messages have a fixed length you could just modify your delimiter.

这篇关于在 Python TCP 流中使用分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆