如何使用 Python 上的套接字制作快速连续的数据流?

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

我正在编写一个代码,其中 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。

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

我的解决方案是使用 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))