# 粘包现象
# 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))