Python异步UDP服务器 [英] Python asyncore UDP server

查看:26
本文介绍了Python异步UDP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Python 编写服务器应用程序,用于侦听请求、处理请求并发送响应.

I am writing server application in Python that listens for requests, processes them, and sends a response.

所有请求/响应都从相同的地址和端口发送到服务器应用程序.我需要同时接收/发送消息,并且服务器需要从/向同一端口和地址接收/发送消息.我找到了一些异步套接字的教程,但只有 TCP 连接的示例.

All req/resp are send from the same address and port to the server application. I need to recv/send messages simultaneously, and the server need to recieve/send messages from/to the same port and address. I found some tutorials for asynchore sockets, but there are only examples for TCP connections.

不幸的是,我需要 UDP.当我在 create 方法中将 SOCK_STREAM 更改为 SOCK_DGRAM 时,出现错误.

Unfortunately, I need UDP. When I change SOCK_STREAM to SOCK_DGRAM in the create method, I get an error.

return getattr(self._sock,name)(*args)
socket.error: [Errno 95] Operation not supported

我尝试使用twisted,但我不知道如何编写发送方部分,该部分可以绑定到与其侦听相同的端口.最后结果是端口被阻塞了.

I tried to use twisted, but I dont know how to write the sender part, which can bind to the same port as its listening. The last result was blocked port.

有什么方法可以使用带有 UDP 的异步套接字或如何使用扭曲从同一端口发送?一些示例将不胜感激.

Is there any way how to use asyncore sockets with UDP or how to use twisted to send from the same port? Some examples will be higly appreciated.

推荐答案

您几乎可以只编写代码的发送和接收部分,它们就会协同工作.请注意,您可以在单个侦听 UDP 套接字上发送和接收 - 您不需要每个都一个(特别是如果您想从同一地址发送和接收).

You can pretty much just write the sending and receiving part of your code and they'll work together. Note that you can send and receive on a single listening UDP socket - you don't need one for each (particularly if you want to send from and receive on the same address).

from __future__ import print_function

from sys import stdout

from twisted.python.log import startLogging
from twisted.internet import reactor
from twisted.internet.protocol import DatagramProtocol

class SomeUDP(DatagramProtocol):
    def datagramReceived(self, datagram, address):
        print(u"Got a datagram of {} bytes.".format(len(datagram)))

    def sendFoo(self, foo, ip, port):
        self.transport.write(
            (u"Foo datagram: {}".format(foo)).encode("utf-8"),
            (ip, port))

class SomeSender(object):
    def __init__(self, proto):
        self.proto = proto

    def start(self):
        reactor.callLater(3, self._send)

    def _send(self):
        self.proto.sendFoo(u"Hello or whatever", b"127.0.0.1", 12345)
        self.start()

startLogging(stdout)

proto = SomeUDP()
reactor.listenUDP(12345, proto)

SomeSender(proto).start()

reactor.run()

这篇关于Python异步UDP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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