基于UDP协议的socket
#serverimport socketsk = socket.socket(type=socket.SOCK_DGRAM)sk.bind(('127.0.0.1',8080))msg,addr = sk.recvfrom(1024)print(msg.decode('utf-8'))sk.sendto(b'bye',addr)sk.close()#clientimport socketsk = socket.socket(type=socket.SOCK_DGRAM)ip_port = ('127.0.0.1',8080)sk.sendto(b'hellog',ip_port)ret,addr = sk.recvfrom(1024)print(ret.decode('utf-8'))
# udp的server 不需要进行监听也不需要建立连接 # 在启动服务之后只能被动的等待客户端发送消息过来 # 客户端发送消息的同时会自带地址信息 # 消息回复的时候,不需要发送信息,还需要把对方的地址发送过去 QQ的UPD聊天代码
#serverimport socketsk = socket.socket(type=socket.SOCK_DGRAM)sk.bind(('127.0.0.1',8080))while True: msg,addr = sk.recvfrom(1024) print(addr) print(msg.decode('utf-8')) info = input('>>>>>>>').encode('utf-8') sk.sendto(info,addr)sk.close()#timimport socketsk = socket.socket(type=socket.SOCK_DGRAM)ip_port = ('127.0.0.1',8080)while True: info = input('Tim: ') info = ('\033[32m来自Tim的消息:%s\033[0m'%info).encode('utf-8') sk.sendto(info,ip_port) msg,addr = sk.recvfrom(1024) print(msg.decode('utf-8'))sk.close()#tiggerimport socketsk = socket.socket(type=socket.SOCK_DGRAM)ip_port = ('127.0.0.1',8080)while True: info = input('Tigger: ') info = ('\033[34m来自Tigger的消息:%s\033[0m'%info).encode('utf-8') sk.sendto(info,ip_port) msg,addr = sk.recvfrom(1024) print(msg.decode('utf-8'))sk.close()
黏包问题
import subprocessret = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)print('stdout: ',ret.stdout.read().decode('gbk'))print('stderr: ',ret.stderr.read().decode('gbk'))