上一篇文章讲到TCP客户端,而这一章则是UDP客户端。
python编写的UDP客户端和TCP客户端相差不大。我们只需要处理两处地方简单的修改,将数据包以UDP的格式发出。
from dataclasses import dataclassfrom http import clientimport socketfrom urllib import responsetarget_host = "127.0.0.1" #修改了目标地址target_hort = 80#a 建立一个socket对象client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)#b 发送一些数据client.sendto("AAABBBCCC",(target_hort,target_host))#c 接受一些数据data,addr = client.recvfrom(4096)print datafrom dataclasses import dataclass from http import client import socket from urllib import response target_host = "127.0.0.1" #修改了目标地址 target_hort = 80 #a 建立一个socket对象 client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #b 发送一些数据 client.sendto("AAABBBCCC",(target_hort,target_host)) #c 接受一些数据 data,addr = client.recvfrom(4096) print datafrom dataclasses import dataclass from http import client import socket from urllib import response target_host = "127.0.0.1" #修改了目标地址 target_hort = 80 #a 建立一个socket对象 client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #b 发送一些数据 client.sendto("AAABBBCCC",(target_hort,target_host)) #c 接受一些数据 data,addr = client.recvfrom(4096) print data
- 在创建套接字对象时,我们将套接字类型改为SOCK_DGRAM(A)。之后我们调用sendto()函数B将数据传到你想发送的服务器上,因UDP是一个无连接状态的传输协议,所以不需要在此之前调用connet()函数。最后一步调用recvfrom()函数C接收返回的数据包。你将接收到回传的数据和远程的主机信息及端口号。
在这里我们将一起学习从零到一。 以上内容来源于当日学习记录。