python,UPD,socket(二) 使用udp 接收消息

时间:2021-08-15 10:07:47
# -*- coding: utf-8 -*-
Section1 接收消息 
 from socket import *
mSocket = socket(AF_INET,SOCK_DGRAM)
mSocket.bind(("",60060))
while True:
   result =  mSocket.recvfrom(1024)
   print(result)
 
这种条件下打印结果如下
(b'\xb9\xfe\xb9\xfe', ('192.168.142.2', 8080))
 
 
Section2 另外一种方法
上面打印结果中包含发送方的IP和端口
 
from socket import *
mSocket = socket(AF_INET,SOCK_DGRAM)
mSocket.bind(("",60060))
while True:
   result =  mSocket.recv(1024)
   print(result)

打印结果如下
b'\xb9\xfe\xb9\xfe'
b'\xb9\xfe\xb9\xfe'
b'\xb9\xfe\xb9\xfe'
 
Section3 解析code
 
# -*- coding: utf-8 -*- from socket import *
mSocket = socket(AF_INET,SOCK_DGRAM)
mSocket.bind(("",60060))
while True:
   result =  mSocket.recv(1024)
   print(result.decode("gb2312"))

这次终于打印出中文了
 
你好你好
你好你好
你好你好