解决tcp粘包问题的两种办法


当前第2页 返回上一页

  服务器端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

# __author__:Kelvin

# date:2019/4/28 21:36

from socket import *

import subprocess

import struct

 

server = socket(AF_INET, SOCK_STREAM)

server.bind(("127.0.0.1", 8000))

server.listen(5)

 

while True:

    conn, addr = server.accept()

    print("创建了一个新的连接!")

    while True:

        try:

            data = conn.recv(1024)

            if not data: break

            res = subprocess.Popen(data.decode("utf-8"), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,

                                   stderr=subprocess.PIPE)

            err = res.stderr.read()

            if err:

                cmd_msg = err

            else:

                cmd_msg = res.stdout.read()

            if not cmd_msg: cmd_msg = "action success!".encode("gbk")

            length = len(cmd_msg)

            conn.send(struct.pack("i", length))

            conn.send(cmd_msg)

        except Exception as e:

            print(e)

            break

  客户端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

# __author__:Kelvin

# date:2019/4/28 21:36

from socket import *

import struct

 

client = socket(AF_INET, SOCK_STREAM)

client.connect(("127.0.0.1", 8000))

while True:

    inp = input(">>:")

    if not inp: continue

    if inp == "quit": break

    client.send(inp.encode("utf-8"))

    length = struct.unpack("i",client.recv(4))[0]

    lengthed = 0

    cmd_msg = b""

    while lengthed < length:

        cmd_msg += client.recv(1024)

        lengthed = len(cmd_msg)

    print(cmd_msg.decode("gbk"))

上述两种方式均可以解决粘包问题。

以上就是解决tcp粘包问题的两种办法的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

angular8如何封装http服务

[http] tcp/ip详解 链路层 网络层 传输层 应用层

http请求的常用方法有哪些

[tcp/ip] 数据链路层-ethereal 抓包分析数据帧

前端获取http状态码400的返回值实例_基础教程

[tcp/ip] 网络层-arp协议

用 // 代替 的好处

前端开发紧密相关的http协议知识

分析影响http性能的常见因素

解决tcp粘包问题的两种办法

更多相关阅读请进入《tcp/ip》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...

    正在狠努力加载,请稍候...