struct模块
park("i",len(msg)) 把数字转成4字节
unpack("i",bytes)[0] 把四字节转换成长度
server端
import struct
import socket
sk = socket.socket()
sk.bind((‘127.0.0.1‘,9090))
sk.listen()
conn,addr = sk.accept()
while True:
s = input(‘>>>‘).encode(‘utf-8‘)
pack_num = struct.pack(‘i‘,len(s))
conn.send(pack_num)
conn.send(s)
conn.close()
sk.close()
client端
import socket
import struct
sk = socket.socket()
sk.connect((‘127.0.0.1‘,9090))
while True:
pack_num = sk.recv(4)
num = struct.unpack(‘i‘,pack_num)[0]
ret = sk.recv(num)
print(ret.decode(‘utf-8‘))
sk.close()
server端
import os
import hmac
import socket
def auth(conn):
msg = os.urandom(32) # # 生成一个随机的字符串
conn.send(msg) # # 发送到client端
result = hmac.new(secret_key, msg) # 处理这个随机字符串,得到一个结果
client_digest = conn.recv(1024) # 接收client端处理的结果
if result.hexdigest() == client_digest.decode(‘utf-8‘):
print(‘是合法的连接‘) # 对比成功可以继续通信
return True
else:
print(‘不合法的连接‘) # 不成功 close
return False
secret_key = b‘alex_sb‘
sk = socket.socket()
sk.bind((‘127.0.0.1‘,9000))
sk.listen()
conn,addr = sk.accept()
if auth(conn):
print(conn.recv(1024))
# 正常的和client端进行沟通了
conn.close()
else:
conn.close()
sk.close()
client端
import hmac
import socket
def auth(sk):
msg = sk.recv(32)
result = hmac.new(key, msg)
res = result.hexdigest()
sk.send(res.encode(‘utf-8‘))
key = b‘alex_s‘
sk = socket.socket()
sk.connect((‘127.0.0.1‘,9000))
auth(sk)
sk.send(b‘upload‘)
# 进行其他正常的和server端的沟通
sk.close()
原文:https://www.cnblogs.com/yuncong/p/9665453.html