python3 udp不黏包但丢数据

时间:2022-12-15 17:57:01
----------------------------------------udp_server.py----------------------------------------
#
coding:utf-8 import socket import subprocess udp_server = socket.socket(type=socket.SOCK_DGRAM) ip_port = ("127.0.0.1", 8001) udp_server.bind(ip_port) from_client_msg, addr = udp_server.recvfrom(1024) print("来自客户端的消息:", from_client_msg.decode("utf-8")) cmd = input(">>>:").strip() res = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) send_bytes = res.stdout.read() udp_server.sendto(send_bytes, addr) print(len(send_bytes)) udp_server.close()


----------------------------------------udp_client.py----------------------------------------
# coding:utf-8
import socket

udp_client = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ("127.0.0.1", 8001)
udp_client.sendto("我是客户端".encode("utf-8"), ip_port)
from_server_msg, addr = udp_client.recvfrom(1024)
print("来自服务端的消息:", from_server_msg.decode("gbk"))
udp_client.close()


执行结果:
Traceback (most recent call last):
  File "F:/2019老男孩周末26期/day08/课下练习/07 udp_黏包测试_client.py", line 7, in <module>
    from_server_msg, addr = udp_client.recvfrom(1024)
OSError: [WinError 10040] 一个在数据报套接字上发送的消息大于内部消息缓冲器或其他一些网络限制,或该用户用于接收数据报的缓冲器比数据报小。

解决方法,可以适当调大客户端接收最大数据的大小.