一、脚本运行环境
系统:ubantu16.04
语言:python3.6
二、创建UDP服务端
1、创建udp socket服务端
# coding=UTF-8
import socket
import pickle
from myobj import Myobj
def main():
"""
# 创建一个套接字接收数据
:return:
"""
# 创建一个套接字
receive_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口 发数据套接字可以不绑定端口,接收数据套接字要绑定端口
localaddr = ("", 7788)
receive_socket.bind(localaddr)
# 接收数据
recv_data = receive_socket.recvfrom(1024)
recv_msg = recv_data[0]
print(pickle.loads(recv_msg))
myobj = pickle.loads(recv_msg)
print(myobj.name)
# 关闭套接字
receive_socket.close()
if __name__ == '__main__':
main()
2、创建myobj类
class Myobj():
def __init__(self):
self.name = "zhangsan"
self.age = 13
备注:由于pickle包存在的bug,如果不在服务端创建一个客户端发送来的对象的类,则服务端在读取到客户端发送来的对象会报错
报错如图所示
三、创建udp客户端
# coding = utf-8
import socket
import pickle
class Myobj():
def __init__(self):
self.name = "zhangsan"
self.age = 13
def create_obj():
myobj = Myobj()
return myobj
def main(myobj):
"""
创建一个套接字
:return:
"""
# 创建一个套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口
udp_socket.bind(("192.168.244.140", 6677))
# 使用套接字收发数据
udp_socket.sendto(pickle.dumps(myobj), ("192.168.244.146", 7788))
# 关闭套接字
udp_socket.close()
if __name__ == '__main__':
myobj = create_obj()
main(myobj)