images/blog-posts

网络篇・UDP通信

返回教程主页

上篇 网络篇・TCP通信

之前我们尝试了TCP服务器与客户端的通讯,现在我们要实现一个服务器,通过UDP协议与客户端程序通讯。

socketserver

和TCP服务器的实现一样,我们使用Python的socketserver库就可以快速实现一个简单的报时务器:

from socketserver import BaseRequestHandler, UDPServer
import time

class TimeHandler(BaseRequestHandler):
    def handle(self):
        print('Got connection from', self.client_address)
        msg, sock = self.request
        resp = time.ctime()
        sock.sendto(resp.encode(), self.client_address)

if __name__ == '__main__':
    serv = UDPServer(('', 8000), TimeHandler)
    serv.serve_forever()

这里我们使用成功self.request获取的套接字sock发送时间刀指定客户端self.client_address

下面我们通过UDP连接的方式去获取服务器报时:

>>> from socket import socket, AF_INET, SOCK_DGRAM
>>> s = socket(AF_INET, SOCK_DGRAM)
>>> s.sendto(b'', ('localhost', 8000))
0
>>> s.recvfrom(8192)
(b'Sun May 23 21:17:54 2021', ('127.0.0.1', 8000))
>>>

ThreadingUDPServer

UDPServer可以快速实现一个简单的服务器,但默认情况下只会得到一个单线程的服务器,不能同时连接多个客户端。使用ThreadingUDPServer则可以快速实现多线程的服务器:

from socketserver import ThreadingUDPServer

   if __name__ == '__main__':
    serv = ThreadingUDPServer(('', 8000), TimeHandler)
    serv.serve_forever()

下篇 网络篇・端口扫描

SUBSCRIBE


🔒 No spam. Unsubscribe any time.

About kk

kk

Vincenzo Antedoro is an engineer who helps those who want to invest in renewables. For the rest he enjoys teaching with the method of learning by doing..

» More about kk