如何在 Python 上使用 socket 制作快速连续的数据流?

How to make a fast continuous stream of data with socket on Python?

提问人:Tom McLean 提问时间:1/12/2021 更新时间:1/13/2021 访问量:1736

问:

我正在编写一个代码,其中 arduino 从加速度计读取数据,将其传递给 python 脚本,然后运行 python 的计算机通过套接字连接将数据发送到另一台计算机。我编写的代码可以一次发送和接收一条消息,速度很慢,但是一旦我尽可能快地(大约 100Hz)完成,服务器端就会只打印第一条消息,但不会再打印了。

这是我的服务器端的代码:

import socket


class server:

    def __init__(self, PORT=9077, MAX_CONNECTIONS=1000, BUFF_SIZE=1024):
        self.s = socket.socket()
        self.HOST = socket.gethostbyname(socket.gethostname())
        self.PORT = PORT
        self.MAX_CONNECTIONS = MAX_CONNECTIONS
        self.BUFF_SIZE = BUFF_SIZE
        self.s.bind((self.HOST, self.PORT))
        self.s.listen(self.MAX_CONNECTIONS)
        self.recievingData = False
        
        print("Starting a server")
        print("IP: " + str(self.HOST))
        print("Port: " + str(self.PORT))

    def recieveData(self):
        self.recievingData = True
        while self.recievingData:
            print("Waiting for data")
            c, addr = self.s.accept()
            print(addr)
            data = b''
            part = c.recv(self.BUFF_SIZE)
            data += part
            while len(part) > self.BUFF_SIZE:
                # print("looping")
                part = c.recv(self.BUFF_SIZE)
                print(len(part))
                data += part
            print(data)
            c.close()

    def stopRecieving(self):
        self.revievingData = False
            
    
    new_server = server()
    new_server.recieveData()

和客户端:

class client:
    
    def __init__(self, HOST="192.168.0.51", PORT=9077):
        self.s = socket.socket()
        self.HOST = HOST
        self.PORT = PORT
        self.s.connect((self.HOST, self.PORT))

    def send_message(self, message):
        message = message.encode()
        sent = self.s.sendall(message)
        print(sent)

而且我基本上只是在每次有新数据要发送时打电话给send_message。

有没有办法提高服务器从同一客户端接收消息的速度?是否需要创建多个线程来接收数据?

Python 套接字 服务器端

评论


答:

1赞 Tom McLean 1/13/2021 #1

我的解决方案是使用 DTP 协议,您可以在不检查是否已收到数据的情况下发送消息。这是在客户端和服务器端使用并用于从客户端接收数据和发送数据来实现的。这样,客户端和服务器之间就没有握手,而且运行速度要快得多。socket.socket(type=SOCK_DGRAM)self.s.recvfrom(self.BUFF_SIZE)self.s.sendto(str(message).encode(), (host, port))

您只需要对输入数据进行一些错误检查。

作为参考,这是我的完整更新代码:

import socket
from socket import SOCK_DGRAM, SO_REUSEADDR
import numpy as np
import threading

class client:
    
    def __init__(self, HOST="192.168.0.51", PORT=9077):
        self.s = socket.socket(type=SOCK_DGRAM)
        self.HOST = HOST
        self.PORT = PORT

    def send_message(self, message):
        self.s.sendto(str(message).encode(), (host, port))

class server:

    def __init__(self, PORT=9077, BUFF_SIZE=1024):
        self.s = socket.socket(type=SOCK_DGRAM)
        self.HOST = socket.gethostbyname(socket.gethostname())
        self.PORT = PORT
        self.MAX_CONNECTIONS = MAX_CONNECTIONS
        self.BUFF_SIZE = BUFF_SIZE
        self.s.bind((self.HOST, self.PORT))
        # self.s.listen(self.MAX_CONNECTIONS)
        self.recievingData = False
        self.recievedData = np.zeros((1,4))
        
        self.thread = threading.Thread(target=self.recieveData)
        self.thread.start()
        # self.s.setblocking(0)
        self.startRecieving()
        
        print("Starting a server")
        print("IP: " + str(self.HOST))
        print("Port: " + str(self.PORT))

    def startRecieving(self):
        self.recievingData = True
        self.recievedData = np.zeros((1,4))
        self.thread = threading.Thread(target=self.recieveData)
        self.thread.start()
        print("Started reading data")
    
    def stopRecieving(self):
        self.recievingData = False
        self.thread.join()
        print("Stopped reading data")


    def recieveData(self):
        self.recievingData = True
        while self.recievingData:
            # print("Waiting for data")
            part, addr = self.s.recvfrom(self.BUFF_SIZE)
            # print(part, addr)
            data = b''
            data += part
            while len(part) > self.BUFF_SIZE:
                # print("looping")
                part = self.s.recvfrom(self.BUFF_SIZE)
                # print(len(part))
                data += part
            self.lastData = data
            print(data)
            as_float = np.array([[float(x.strip()) for x in data.decode().split(',')]])
            self.recievedData = np.vstack((self.recievedData, as_float))