【发布时间】:2015-12-02 10:40:34
【问题描述】:
我可以在异步中编写 UDP 客户端/服务器应用程序吗?我已经使用 TCP 编写了一个。我的愿望是将它与对 UDP 的支持集成。
我的问题以前没有被以下人问过/回答: Python asyncore UDP server
【问题讨论】:
标签: python-2.7 sockets tcp udp asyncore
我可以在异步中编写 UDP 客户端/服务器应用程序吗?我已经使用 TCP 编写了一个。我的愿望是将它与对 UDP 的支持集成。
我的问题以前没有被以下人问过/回答: Python asyncore UDP server
【问题讨论】:
标签: python-2.7 sockets tcp udp asyncore
是的,你可以。这是一个简单的例子:
class AsyncoreSocketUDP(asyncore.dispatcher):
def __init__(self, port=0):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
self.bind(('', port))
# This is called every time there is something to read
def handle_read(self):
data, addr = self.recvfrom(2048)
# ... do something here, eg self.sendto(data, (addr, port))
def writable(self):
return False # don't want write notifies
这应该足以让您入门。查看asyncore 模块的内部以获得更多想法。
小提示:asyncore.dispatcher 将套接字设置为非阻塞。如果
您想快速将大量数据写入套接字而不会导致
错误你必须做一些依赖于应用程序的缓冲
阿拉asyncore.dispatcher_with_send。
感谢这里的(稍微不准确的)代码让我开始: https://www.panda3d.org/forums/viewtopic.php?t=9364
【讨论】:
self.sendto(data, (addr, port))
经过长时间的搜索,答案是否。 Asyncore 假设底层套接字是面向连接的,即 TCP。
【讨论】:
您好,感谢@bw1024 指出了正确的方向,我将添加受您的、pandas 和 python asyncore 文档启发的解决方案。
我的用例是从 UDP 流中捕获一些 JSON
`
导入套接字 导入json 导入异步
UDP_IP = '127.0.0.1' UDP_PORT = 2000
类 AsyncUDPClient(asyncore.dispatcher): def init(自身、主机、端口): asyncore.dispatcher.init(self) self.create_socket(socket.AF_INET,socket.SOCK_DGRAM) self.bind((主机,端口)) print("正在连接.. host = '{0}'' port = '{1}'" .format(host, str(port)))
def handle_connect(self):
print("connected")
def handle_read(self):
data = self.recv(1024)
y = json.loads(data)
print("PM 2.5 ug/m^3 async : %s "% y['PM25MassPerM3'])
def writable(self):
return False;
client = AsyncUDPClient(UDP_IP, UDP_PORT)
asyncore.loop()
`
P.S 不确定为什么代码没有被正确格式化,它在 python 3.6.9 上运行,这是一个link 的要点
【讨论】: