Python socket编程之二:【struct.pack】&【struct.unpack】
import struct """通过 socket 的 send 和 recv 只能传输 str 格式的数据""" """struct.pack""" a1 = 10 a2 = 100 str = struct.pack("ii", a1, a2) print('str = ', str) """struct.unpack""" a1, a2 = struct.unpack("ii", str) print('a1 = ', a1) print('a2 = ', a2)
args = ("H", "ello world ", 5) struct.pack("c12si", *args) # 等价于 struct.pack("c12si", "H", "ello world ", 5)
一个完整的实例
- 1.f1.py
# -*- coding: utf-8 -*- """f1.py""" """Python socket 编程实例""" import socket import struct ######################################################################## class sckt: """变量名缩写法,sckt 代表 socket""" #---------------------------------------------------------------------- def __init__(self, host = '192.168.1.3', port = 12345): """地址与端口初始化""" self.host = host self.port = port #---------------------------------------------------------------------- def run_server(self): """服务器""" sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) """声明 TCP/IP 报文""" sckt.bind((self.host, self.port)) """绑定地址与端口""" sckt.listen(5) """启动监听""" connection, address = sckt.accept() """开启接收""" if connection.recv(1024) == b'Link': """对接信号,b'' 代表二进制形式的字符串,socket 的要求""" print('Linking server successed!') ld = [1, 2, 3] """Listdata,数据格式 3i = [int,int,int]""" sd = struct.pack('3i', ld[0], ld[1], ld[2]) """根据 ld 数据格式 pack 为 socket 传输格式 3i""" connection.send(sd) """向客户端发送数据""" else: connection.send(b'Cut off the connection!') connection.close() """关闭链接""" #---------------------------------------------------------------------- def run_client(self, message = b'Link'): """客户端""" sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) """声明 TCP/IP 报文""" sckt.connect((self.host, self.port)) """链接服务器""" sckt.send(message) """向服务器发送数据""" sd = sckt.recv(1024) """接收服务器数据""" ld = struct.unpack('3i', sd) """解包""" print(ld) sckt.close() """关闭连接"""
- 2.f2.py
# -*- coding: utf-8 -*- """f2.py""" """载入模块""" import sys sys.path.append('D:/360data/重要数据/桌面') import f1 """地址初始化""" F1 = f1.sckt() """运行服务器""" F1.run_server() """运行客户端""" F1.run_client()