tcp和udp和黏包

Tcp建立连接的过程

server端

# import socket
#
# sk = socket.socket()  #创建一个socket对象
# sk.bind(('127.0.0.1',8088))  #绑定ip地址和端口
# sk.listen()
# while 1:
#     conn,addr = sk.accept()    #等待建立连接
#                                 #阻塞 直到连接建立才往下执行
#     while 1:
#         ret = conn.recv(1024).decode('utf-8') #阻塞 知道收到 才往下执行
#         print(ret)
#         if 'bye' in ret:
#             conn.send(b'bye')
#             break
#         info = input('>>>')
#         conn.send(info.encode('utf-8'))
#
# conn.close()         #断开连接
# sk.close()     # 关闭socket对象 如果不关闭 仍能传输

client端

# import socket
# sk = socket.socket()
# sk.connect(('127.0.0.1',8088))
#
# while 1:
#     msg = input('>>>')
#     sk.send(('client1'+msg).encode('utf-8'))
#     ret = sk.recv(1024).decode('utf-8')
#     print(ret)
#     if ret == 'bye':
#         sk.send(b'bye')
#         break
#
# sk.close()

 

Udp协议

server端

import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1',8088))
while 1:
    msg,addr = sk.recvfrom(1024)
    print(addr)
    print(msg.decode('utf-8'))
    info = input(">>>").encode('utf-8')
    sk.sendto(info,addr)

sk.close()

client端

import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
ip_port = (('127.0.0.1',8088))
while 1:
    info = input('1:')
    info = ('\033[34m来自1的消息:%s\033[0m'%info).encode('utf-8')
    sk.sendto(info,ip_port)
    msg,addr = sk.recvfrom(1024)
    print(msg.decode('utf-8'))

sk.close()

 

黏包

黏包只存在tcp协议中,tcp内部优化算法,报文分片传输,

黏包的原因:

1,发送大于接收的字节数,后续信息会在下次发送。

2,连续发送短报文,tcp会自动处理成一段报文发送

黏包的解决:借用struc模块

server端

# import socket
# import struct
# sk = socket.socket()
# sk.bind(('127.0.0.1',8088))
# sk.listen()
#
# conn,addr = sk.accept()
# while 1:
#
#     cmd = input('>>>')
#     if cmd == 'q':
#         break
#     conn.send(cmd.encode('gbk'))
#     num = conn.recv(4)           #接收4个字节
#     num = struct.unpack('i',num)[0]    #转成数据长度
#     ret = conn.recv(int(num)).decode('gbk')
#     print(ret)
#
# conn.close()
# sk.close()

client端

# import socket
# import subprocess
# import struct
# sk = socket.socket()
# sk.connect(('127.0.0.1',8088))
# while 1:
#     cmd = sk.recv(1024).decode('gbk')
#     if cmd == 'q':
#         break
#     res = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
#     std_out = res.stdout.read()
#     std_err = res.stderr.read()
#     num = len(std_out)+len(std_err)
#     num_by = struct.pack('i',num)
#     sk.send(num_by)
#     sk.send(std_out)
#     sk.send(std_err)
# sk.close()

 

posted @ 2020-12-20 19:42  木_糖  阅读(101)  评论(0编辑  收藏  举报