简体   繁体   English

Python异步UDP服务器

[英]Python asyncore UDP server

I am writing server application in Python that listens for requests, processes them, and sends a response. 我正在用Python编写服务器应用程序,以侦听请求,处理请求并发送响应。

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. 我找到了一些有关异步套接字的教程,但是只有TCP连接的示例。

Unfortunately, I need UDP. 不幸的是,我需要UDP。 When I change SOCK_STREAM to SOCK_DGRAM in the create method, I get an error. 在create方法中将SOCK_STREAM更改为SOCK_DGRAM时,出现错误。

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

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. 最后结果是端口被阻塞。

Is there any way how to use asyncore sockets with UDP or how to use twisted to send from the same port? 有什么方法可以将异步套接字与UDP一起使用,或者如何使用twisted从同一端口发送? Some examples will be higly appreciated. 一些例子将被赞赏。

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). 请注意,您可以在单个侦听UDP套接字上发送和接收-不需要每个套接字(特别是如果要在同一地址发送和接收)。

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()

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

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