python-套接字编程之udp
使用udp协议
服务端:
#!/usr/bin/python3 # coding:utf-8 # Auther:AlphaPanda # Description:UDP服务端 # Version:1 # Date:Mon Dec 2 03:24:46 EST 2019 ### 服务端 import socket # 1 创建udp对象 tpye = SOCK_DGRAM 代表udp协议 sk = socket.socket( type = socket.SOCK_DGRAM ) # 2 绑定Ip和端口(在网络中注册主机,让其他的服务器可以找到该主机) sk.bind(("127.0.0.1",9000)) # 3 收发数据的逻辑 """udp的服务端,第一次只能接收数据""" while True: msg,cli_addr = sk.recvfrom(1024) print(msg.decode("utf-8")) message = input("server:>>>") if message == "q": break else: sk.sendto(message.encode("utf-8"),cli_addr) # 4 关闭udp连接 sk.close()
客户端:
#!/usr/bin/python3 # coding:utf-8 # Auther:AlphaPanda # Description:udp客户端 # Version::1 # Date:Mon Dec 2 03:28:23 EST 2019 """ import socket sk = socket.socket( type = socket.SOCK_DGRAM) sk.sendto("hello".encode("utf-8"),("127.0.0.1",9000)) msg,dest_addr = sk.recvfrom(1024) print(msg.decode("utf-8")) sk.close() """ # 导入模块 import socket # 生成UDP类型的套接字对象 sk = socket.socket( type = socket.SOCK_DGRAM ) # 逻辑判断,收发数据的代码 while True: message = input("client:>>>") if message == "q": break else: sk.sendto(message.encode("utf-8"),("127.0.0.1",9000)) msg,ser_addr = sk.recvfrom(1024) print(msg.decode("utf-8")) # 关闭UDP连接 sk.close()
念念不忘,必有回响。