Python3 UDP消息通信

73 阅读1分钟

UDP消息通信

来源:blog.csdn.net/weixin_3985…

udp服务端:server.py
#
import socket
# type=socket.SOCK_DGRAM => 返回udp协议对象
# 1.创建udp对象
sk = socket.socket(type=socket.SOCK_DGRAM)
 
# 2.绑定地址端口号
sk.bind( ("127.0.0.1",9000) )
 
# 3.接受消息(udp作为服务端的时候,第一次一定是接受消息)
while True:
	# 接受消息
	msg,cli_addr = sk.recvfrom(1024)
	print(msg.decode("utf-8"))
	print(cli_addr)
 
# 服务端给客户端发消息
message = input("服务端要发送的消息:")
sk.sendto(message.encode("utf-8"), cli_addr)
 
 
# 4.关闭连接
sk.close()
udp客户端:client.py
#
import socket
# type=socket.SOCK_DGRAM => 返回udp协议对象
# 1.创建udp对象
sk = socket.socket(type=socket.SOCK_DGRAM)
 
# 2.发送数据
while True:
	# 发送数据
	message = input("请输入客户端发送的消息")
	sk.sendto(message.encode("utf-8") , ("127.0.0.1",9000) )
 
# 客户端接受服务端发过来的数据
msg, addr = sk.recvfrom(1024)
print(msg.decode("utf-8"))
 
 
# 3.关闭连接
sk.close()