龙空技术网

Python UDP 协议网络编程《一》

Candy.W 180

前言:

当前姐妹们对“pythonsocketudp”大约比较着重,你们都想要知道一些“pythonsocketudp”的相关文章。那么小编在网络上网罗了一些关于“pythonsocketudp””的相关文章,希望同学们能喜欢,你们快快来了解一下吧!

今日主题:UDP协议层 Python 是如何收发消息的。

1、基础内容了解

TCP & UDP 这两种协议都是传输层的协议,Socket 是传输供给应用层的编程接口,所以Socket 编程就分为TCP & UDP 编程两类。TCP 是面向连接的,传输数据是安全的,稳定的,效率相对较低。SOCK_STREAM表示是TCP的socket。UDP 是面向无连接的,传输数据是不安全的,效率较高。SOCK_DGRAM表示是UDP的socket。UDP协议称为用户数据报协议(user data protocol) , UDP 为应用程序提供了一种无需建立连接就可以发送封装的 IP 数据报的方法 . 因此:传输数据之前源端和终端不建立连接。socket: 套接字是一个模块,我们用它来完成收发信息。ip和端口: 要给谁发送消息就写谁的ip,这里指的是server 端。encode: 就是编码,把字符串转换成字节,因为sendto方法的格式.(反之decode就是解码),本文以utf-8为编码来演示。

2、UDP 发送消息的实现步骤

导包socket模块创建socket对象确定好要发送的目标ip,端口确定要发送的内容用socket对象的sendto方法发送关闭socket对象

client.py 发送消息端的Python 代码实现:

 1from socket import socket,AF_INET,SOCK_DGRAM 2udp_socket = socket(AF_INET, SOCK_DGRAM)#建议upd连接 3local_address = ('127.0.0.1', 8000)#定义了本机的ip and port 4udp_socket.bind(local_address)#绑定本机的ip and port 5 6def udp_send_msg(): 7    while 1:#无限接收 8        resvice_address=('127.0.0.1',9000) #定义了接收消息机器的ip and port 9        data=input("<<<:")#接收键盘的输出信息10        udp_socket.sendto(str(data).encode("utf-8"),resvice_address)#向接收消息机器发送消息11    udp_socket.close()1213if __name__ == '__main__':14 print("the client of ip:%s and port:%d is running"%(local_address))15 udp_send_msg()

运行后结果:

the client of ip:127.0.0.1 and port:8000 is running

<<<:hello tony

<<<:good job

<<<:

3、UDP接收消息的实现步骤

导包socket文件创建socket对象绑定地址和端口接受数据,等待关闭socket对象

server.py 接收消息端的Python 代码实现:

 1from socket import socket,AF_INET,SOCK_DGRAM 2local_address = ('127.0.0.1', 9000)  # 定义本服务器的ip and port 3udp_socket = socket(AF_INET, SOCK_DGRAM)#建立udp socker连接 4 5def recv_server(): 6    udp_socket.bind(local_address)#服务端绑定ip and port 7    recv_data = udp_socket.recvfrom(1024)#收数据等待 8    print('接收的内容:', recv_data[0].decode('utf-8'))#显示收到的信息 9    print('发送人的地址:', recv_data[1])#显示收到的信息101112if __name__ == '__main__':13    print("the server ip:%s and the port:%d is running"%(local_address))14    while True:15       recv_server()16    udp_socket.close()

运行后结果:

the server ip:127.0.0.1 and the port:9000 is running

接收的内容:hello tony

发送人 的地址:('127.0.0.1', 8000)

接收的内容:good job

发送人 的地址:('127.0.0.1', 8000)

标签: #pythonsocketudp #python协议分析