Python套接字接收双打

问题描述 投票:1回答:2

我需要一个python程序来使用TCP连接(到另一个程序)来检索9个字节的集合。

九个字节中的第一个代表一个char,其余代表一个double。

如何从python套接字中提取此信息?我是否必须手动进行数学转换以转换流数据还是有更好的方法吗?

python sockets casting double
2个回答
3
投票

看看python struct

http://docs.python.org/library/struct.html

所以像

from struct import unpack

unpack('cd',socket_read_buffer)

--> ('c', 3.1415)

小心Endianness。


0
投票

如果客户端和服务器都是用python编写的,我建议你使用pickle。它允许您将python变量转换为字节,然后返回到原始类型的python变量。

#SENDER
import pickle, struct

#convert the variable to bytes with pickle
bytes = pickle.dumps(original_variable)
#convert its size to a 4 bytes int (in bytes)
#I: 4 bytes unsigned int
#!: network (= big-endian)
length = struct.pack("!I", len(bytes))
a_socket.sendall(length)
a_socket.sendall(bytes)

#RECEIVER
import pickle, struct

#This function lets you receive a given number of bytes and regroup them
def recvall(socket, count):
    buf = b""
    while count > 0:
        newbuf = socket.recv(count)
        if not newbuf: return None
        buf += newbuf
        count -= len(newbuf)
    return buf


length, = struct.unpack("!I", recvall(socket, 4)) #we know the first reception is 4 bytes
original_variable = pickle.loads(recval(socket, length))
© www.soinside.com 2019 - 2024. All rights reserved.