简体   繁体   English

保持套接字连接,数据频率不规则

[英]maintaining socket connection, irregular data frequency

I'd like to create a python socket (or SocketServer) that, once connected to a single device, maintains an open connection in order for regular checks to be made to see if any data has been sent. 我想创建一个python套接字(或SocketServer),该套接字一旦连接到单个设备,便会保持开放连接,以便进行常规检查以查看是否已发送任何数据。 The socket will only listen for one connection. 套接字仅侦听一个连接。

Eg: 例如:

def get_data(conn):
    response='back atcha'
    data = conn.recv(1024)
    print 'get_data:',data
    if data:
        conn.send(response)

s = open_socket()
conn, addr = s.accept()
while True:
    print 'running'
    time.sleep(1)
    get_data(conn)
    #do other stuff

Once the server socket is bound and the connection has been accepted, the socket blocks when running a .recv until either the connecting client sends some data or closes its socket. 绑定服务器套接字并接受连接后,套接字将在运行.recv时阻塞,直到连接的客户端发送一些数据或关闭其套接字为止。 As I am waiting for irregular data (could be seconds, could be a day), and the program needs to perform other tasks in the meantime, this blocking is a problem. 由于我正在等待不规则的数据(可能是几秒钟,可能是一天),并且程序需要同时执行其他任务,因此这种阻塞是个问题。

I don't want the client to close its socket, as it may need to send (or receive) data at any time to (from) the server. 我不希望客户端关闭其套接字,因为它可能需要随时向(从)服务器发送(或接收)数据。 Is the only solution to run this in a separate thread, or is there a simple way to setup the client/server sockets to maintain the connection forever (and is this safe? It'll be running on a VLAN) while not blocking when no data has been received? 是唯一在单独线程中运行此解决方案的解决方案,还是有一种简单的方法来设置客户端/服务器套接字以永久保持连接(这是否安全?它将在VLAN上运行),而在没有时不阻塞数据已收到?

You're looking for non-blocking I/O, also called asynchronous I/O. 您正在寻找非阻塞I / O,也称为异步I / O。 Using a separate thread which blocks on this is very inefficient but it's pretty straightforward. 使用单独的线程对此进行阻止是非常低效的,但非常简单。

For a Python asynchronous I/O framework I highly recommend Twisted . 对于Python异步I / O框架,我强烈建议Twisted Also check out asyncore which comes with the standard library. 还请检查标准库随附的asyncore

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

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