• TCP协议的粘包现象和解决方法


    # 粘包现象

    # server
    import socket

    sk = socket.socket()
    sk.bind(('127.0.0.1', 8005))
    sk.listen()

    conn, addr = sk.accept()
    conn.send(b'123')
    conn.send(b'123')

    # client
    import time
    import socket

    sk = socket.socket()

    sk.connect(('127.0.0.1', 8005))

    time.sleep(5)
    msg1 = sk.recv(1024).decode('utf-8')
    msg2 = sk.recv(1024).decode('utf-8')
    print(msg1)
    print(msg2)

    # 客户端接收到的信息,两条黏在了一起
    # 123123
    #
    # 这就是粘包现象

    解决方法:

    # 利用struct模块
    # server
    import struct
    import socket

    sk = socket.socket()
    sk.bind(('127.0.0.1', 8005))
    sk.listen()

    def func(msg):
    msg = msg
    len_msg = len(msg)
    struct_msg = struct.pack('i', len_msg)
    conn.send(struct_msg)
    conn.send(msg)

    conn, addr = sk.accept()


    msg1 = '这是第一条信息'.encode('utf-8')
    msg2 = '这是第二条信息'.encode('utf-8')

    func(msg1)
    func(msg2)


    # client
    import struct
    import socket
    import time

    sk = socket.socket()
    sk.connect(('127.0.0.1', 8005))

    time.sleep(10)

    def func(sk):
    struct_msg = sk.recv(4)
    struct_msg = struct.unpack('i', struct_msg)[0]
    msg = sk.recv(int(struct_msg)).decode('utf-8')
    return msg

    print(func(sk))
    print(func(sk))

  • 相关阅读:
    CSS边框
    各大网站注册的用处(个人看法)
    20121011 外边距
    20120921碎碎念
    20121011 CSS一
    20120919碎碎念
    CSS 文本装饰属性
    外边距合并
    EverBox开发笔记1
    “Core Data”中的“dynamic implementation”
  • 原文地址:https://www.cnblogs.com/xuyuwei/p/11536668.html
Copyright © 2020-2023  润新知