# 服务端import socketserver = socket.socket(type=socket.soCK_DGRAM) # UDP协议server.bind(('127.0.0.1',8080))# UDP不需要设置半连接池 它也没有半连接池的概念# 因为没有双向通道 不需要accept 直接就是通信循环while True: data,addr = server.recvfrom(1024) print('数据:',data) # 客户端发来的消息 print('地址:',addr) # 客户端的地址 server.sendto(data.upper(),addr)# 客户端import socketclIEnt = socket.socket(type=socket.soCK_DGRAM)# 不需要建立连接 直接进入通信循环server_address = ('127.0.0.1',8080)while True: clIEnt.sendto(b'hello',server_address) data,addr = clIEnt.recvfrom(1024) print('服务端发来的数据',data) print('服务端的地址',addr)三、UDP与TCP之间的区别 UDP协议客户端允许发空 UDP协议不会粘包 UDP协议服务端不存在的情况下,客户端照样不会报错 UDP协议支持并发 四、UDP实现简易版本QQ
# 服务端import socketserver = socket.socket(type=socket.soCK_DGRAM)server.bind(('127.0.0.1',8080))while True: data,addr = server.recvfrom(1024) print(data.decode('utf-8')) msg = input('>>>:') server.sendto(msg.encode('utf-8'),addr) # 客户端1import socketclIEnt = socket.socket(type=socket.soCK_DGRAM)server_address = ('127.0.0.1',8080)while True: msg = input('>>>:') msg = '来自客户端1的消息:%s'%msg clIEnt.sendto(msg.encode('utf-8'),server_addr = clIEnt.recvfrom(1024) print(data.decode('utf-8'))# 客户端2import socketclIEnt = socket.socket(type=socket.soCK_DGRAM)server_address = ('127.0.0.1',8080)while True: msg = input('>>>:') msg = '来自客户端2的消息:%s'%msg clIEnt.sendto(msg.encode('utf-8'),server_addr = clIEnt.recvfrom(1024) print(data.decode('utf-8'))# 客户端3import socketclIEnt = socket.socket(type=socket.soCK_DGRAM)server_address = ('127.0.0.1',8080)while True: msg = input('>>>:') msg = '来自客户端3的消息:%s'%msg clIEnt.sendto(msg.encode('utf-8'),server_addr = clIEnt.recvfrom(1024) print(data.decode('utf-8')) # 客户端4import socketclIEnt = socket.socket(type=socket.soCK_DGRAM)server_address = ('127.0.0.1',8080)while True: msg = input('>>>:') msg = '来自客户端4的消息:%s'%msg clIEnt.sendto(msg.encode('utf-8'),server_addr = clIEnt.recvfrom(1024) print(data.decode('utf-8')) # 客户端5import socketclIEnt = socket.socket(type=socket.soCK_DGRAM)server_address = ('127.0.0.1',8080)while True: msg = input('>>>:') msg = '来自客户端5的消息:%s'%msg clIEnt.sendto(msg.encode('utf-8'),server_addr = clIEnt.recvfrom(1024) print(data.decode('utf-8'))总结
以上是内存溢出为你收集整理的UDP通信全部内容,希望文章能够帮你解决UDP通信所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)