相对于tcp编程,twisted提供的udp编程要简单的多,我们不许要定义协议工厂类,仅需要实现DatagrampProtol协议类。
服务器端代码:

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 14 10:34:40 2022

@author: xjmt
"""

import socket
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

class udpServer(DatagramProtocol):
    def __init__(self):
        #模拟需要传入的数据
        self.num = 0
        
    def sendnum(self, addr):
        # 将数据发送给客户端,基于udp的性质,发送时需要输入客户端地址
        self.transport.write(str(self.num).encode(),addr)
        self.num += 1
            
    def startProtocol(self):
        print("服务端启动")
        
    def datagramReceived(self,data,addr):
        #输出客户端传入内容
        print(f"received {data!r} from {addr}")
        #返回第一段初始数据给客户端
        self.sendnum(addr)
        


if __name__ == "__main__":
    portSocket =  socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    portSocket.setblocking(False)
    portSocket.bind(("127.0.0.1", 5678))
    #将sokcet描述符信息添加到反应器
    port = reactor.adoptDatagramPort(portSocket.fileno(), socket.AF_INET, udpServer())
    #关闭socket描述符,
    portSocket.close()
    #reactor.listenUDP(5678, udpServer())    
    reactor.run()

客户端代码:

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 14 10:34:55 2022

@author: xjmt
"""

import time
from twisted.internet.protocol import ConnectedDatagramProtocol
from twisted.internet import reactor

class udpClient(ConnectedDatagramProtocol):
    def __init__(self):
        #模拟收到的数据量
        self.num = 0
        
    def startProtocol(self):
        host = "127.0.0.1"
        port = 5678

        self.transport.connect(host, port)
        print("开始向服务器 %s port %d 请求数据" % (host, port))
        self.transport.write(b"hello")  # no need for address
        
    def datagramReceived(self, datagram, addr):
        # 每收到一份数据记录一次
        self.num += 1
        # 输出服务端传入内容
        print("服务端 %s:%s 说: %s" % (addr[0],addr[1],datagram.decode()))
        time.sleep(1)
        # 当收到10数据后,再次请求
        self.transport.write(b"hello")


if __name__ == "__main__":
    #不需要设定监听的端口  
    reactor.listenUDP(0, udpClient())
    reactor.run()