Python套接字接收双打

时间:2012-05-08 16:54:14

标签: python sockets casting double

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

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

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

2 个答案:

答案 0 :(得分:3)

看看python struct

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

类似

from struct import unpack

unpack('cd',socket_read_buffer)

--> ('c', 3.1415)

小心Endianness。

答案 1 :(得分: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))