UDP client and server with Twisted Python

前端 未结 2 489
北海茫月
北海茫月 2021-02-01 10:53

I want to create a server and client that sends and receives UDP packets from the network using Twisted. I\'ve already written this with sockets in Python, but want to take adva

相关标签:
2条回答
  • 2021-02-01 11:34

    Just like the server example above, there is a client example to. This should help you get started:

    • https://twistedmatrix.com/documents/current/core/howto/udp.html
    • https://github.com/twisted/twisted/blob/trunk/docs/core/examples/echoclient_udp.py

    Ok, here is a simple heart beat sender and receiver using datagram protocol.

    from twisted.internet.protocol import DatagramProtocol
    from twisted.internet import reactor
    from twisted.internet.task import LoopingCall
    import sys, time
    
    class HeartbeatSender(DatagramProtocol):
        def __init__(self, name, host, port):
            self.name = name
            self.loopObj = None
            self.host = host
            self.port = port
    
        def startProtocol(self):
            # Called when transport is connected
            # I am ready to send heart beats
            self.loopObj = LoopingCall(self.sendHeartBeat)
            self.loopObj.start(2, now=False)
    
        def stopProtocol(self):
            "Called after all transport is teared down"
            pass
    
        def datagramReceived(self, data, (host, port)):
            print "received %r from %s:%d" % (data, host, port)
    
    
        def sendHeartBeat(self):
            self.transport.write(self.name, (self.host, self.port))
    
    
    
    class HeartbeatReciever(DatagramProtocol):
        def __init__(self):
            pass
    
        def startProtocol(self):
            "Called when transport is connected"
            pass
    
        def stopProtocol(self):
            "Called after all transport is teared down"
    
    
        def datagramReceived(self, data, (host, port)):
            now = time.localtime(time.time())  
            timeStr = str(time.strftime("%y/%m/%d %H:%M:%S",now)) 
            print "received %r from %s:%d at %s" % (data, host, port, timeStr)
    
    
    
    heartBeatSenderObj = HeartbeatSender("sender", "127.0.0.1", 8005)
    
    reactor.listenMulticast(8005, HeartbeatReciever(), listenMultiple=True)
    reactor.listenMulticast(8005, heartBeatSenderObj, listenMultiple=True)
    reactor.run()
    

    The broadcast example simply modifies the above approach:

    from twisted.internet.protocol import DatagramProtocol
    from twisted.internet import reactor
    from twisted.internet.task import LoopingCall
    import sys, time
    
    class HeartbeatSender(DatagramProtocol):
        def __init__(self, name, host, port):
            self.name = name
            self.loopObj = None
            self.host = host
            self.port = port
    
        def startProtocol(self):
            # Called when transport is connected
            # I am ready to send heart beats
            self.transport.joinGroup('224.0.0.1')
            self.loopObj = LoopingCall(self.sendHeartBeat)
            self.loopObj.start(2, now=False)
    
        def stopProtocol(self):
            "Called after all transport is teared down"
            pass
    
        def datagramReceived(self, data, (host, port)):
            print "received %r from %s:%d" % (data, host, port)
    
    
        def sendHeartBeat(self):
            self.transport.write(self.name, (self.host, self.port))
    
    
    
    class HeartbeatReciever(DatagramProtocol):
        def __init__(self, name):
            self.name = name
    
        def startProtocol(self):
            "Called when transport is connected"
            self.transport.joinGroup('224.0.0.1')
            pass
    
        def stopProtocol(self):
            "Called after all transport is teared down"
    
    
        def datagramReceived(self, data, (host, port)):
            now = time.localtime(time.time())  
            timeStr = str(time.strftime("%y/%m/%d %H:%M:%S",now)) 
            print "%s received %r from %s:%d at %s" % (self.name, data, host, port, timeStr)
    
    
    
    heartBeatSenderObj = HeartbeatSender("sender", "224.0.0.1", 8005)
    
    reactor.listenMulticast(8005, HeartbeatReciever("listner1"), listenMultiple=True)
    reactor.listenMulticast(8005, HeartbeatReciever("listner2"), listenMultiple=True)
    reactor.listenMulticast(8005, heartBeatSenderObj, listenMultiple=True)
    reactor.run()
    
    0 讨论(0)
  • 2021-02-01 11:52

    Check out the echoclient_udp.py example.

    Since UDP is pretty much symmetrical between client and server, you just want to run reactor.listenUDP there too, connect to the server (which really just sets the default destination for sent packets), then transport.write to send your packets.

    0 讨论(0)
提交回复
热议问题