一、server端
import socket sk = socket.socket(type=socket.SOCK_DGRAM) sk.bind(('127.0.0.1',8080)) msg,addr = sk.recvfrom(1024) # 接收消息 print(msg,addr) sk.sendto(b'hello',addr) sk.close()
二、client端
import socket sk = socket.socket(type=SOCK_DGRAM) sk.sendto(b'hello',('127.0.0.1',8080)) msg,addr = sk.recvfrom(1024) print(msg) sk.close()
三、基于UDP的聊天小工具
server端
import socket sk = socket.socket(type=socket.SOCK_DGRAM) sk.bind(('127.0.0.1',9090)) while True: msg, addr = sk.recvfrom(1024) print('来自[%s:%s]的消息--%s'%(addr[0],addr[1],msg.decode('utf-8'))) inp = input('>>>') sk.sendto(inp.encode('utf-8'),addr) sk.close()
client端
import socket sk = socket.socket(type=socket.SOCK_DGRAM) addr = ('127.0.0.1',9090) while True: msg = input('>>>') sk.sendto(msg.encode('utf-8'),addr) msg_recv, addr = sk.recvfrom(1024) print(msg_recv.decode('utf-8')) sk.close()
要启动聊天,需要先运行server端代码,在运行client端代码