Python Tcp数据传输

2017-09-04  本文已影响678人  sky2016

需要用到python中的socket模块和struct模块,所以首先需要导入进来

 import socket
 import struct

接着是连接

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 7199)
test_getalldisk(s)

在这里假设C中通讯协议头定义为:

struct Header
{
  unsigned short wMajorFunction;    /// 主命令
  unsigned short wMinorFunction;    /// 副命令
  unsigned long dwRetStatus;        /// 返回值
  unsigned long dwDataSize;     /// 头后面数据长度
};

传输时wMajorFunction值需要设为50,其他值为0,则用python struct模块进行包装:

data = struct.pack('>HHLL', 50, 0, 0, 0)

struct模块用法可以参考:
https://docs.python.org/3/library/struct.html#format-characters

test_getalldisk()函数定义:

def test_getalldisk(s):
  header_size = struct.calcsize('>HHLL')
  print header_size

  data = struct.pack('>HHLL', 50, 0, 0, 0)

  s.sendall(data) #发送请求数据包头

  recv_header = recvall(s, header_size) #接收回应数据包头
  if len(recv_header) != header_size:
      return

  header = struct.unpack('>HHLL', recv_header)
  body_size = int(header[-1]) #后续数据长度

  body = recvall(s, body_size) #接收后续数据
  print body

python socket 提供了sendall()函数,却没有提供recvall()函数,只好自己实现一个:

def recvall(s, recv_size):
  recv_buffer = []
  while 1:
    data = s.recv(recv_size)
    if not data:
        break
    recv_buffer.extend(data)
    if len(recv_buffer) == recv_size:
        break
  return ''.join(recv_buffer)
上一篇 下一篇

猜你喜欢

热点阅读