黏包现象之udp

时间:2021-07-19 20:42:25

老师的博客:http://www.cnblogs.com/Eva-J/articles/8244551.html

server端

import socket
import subprocess
server=socket.socket(type=socket.SOCK_DGRAM)
ip_port=('192.168.43.155',8895)
server.bind(ip_port)
while 1:
    message,address=server.recvfrom(1024)
    if message==b'q':
        break
    get=subprocess.Popen(message.decode('utf-8'),
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    server.sendto(get.stdout.read(),address)
    print(get.stdout.read())
    server.sendto(get.stderr.read(),address)
    print(get.stderr.read())
server.close()

client端

import socket
ip_port=('192.168.43.155',8895)
client=socket.socket(type=socket.SOCK_DGRAM)
while 1:
    cmd=input('<<:').encode('utf-8')
    if cmd==b'q':break
    client.sendto(cmd,ip_port)
    message,addresss=client.recvfrom(4096)
    conformation,site=client.recvfrom(4096)
    print(message.decode('gbk'),'out')
    print(conformation.decode('gbk'),'erre')
client.close()

注意 udp永不黏包,但是如果传送的数据包大于bufsize将会报错,及上面server端的信息发送的长度不能超过4096,否则报错