通过套接字连接发送浮点数组

时间:2018-05-23 18:15:52

标签: python python-3.x sockets

我有一个简单的客户端/服务器套接字设置,我正在测试。从client =>发送字符串值服务器很容易使用:

bytes(my_string, "UTF-8")

但是,现在我正在尝试发送一个数组(一些浮点数),我收到此错误:

Traceback (most recent call last):
  File "client.py", line 26, in <module>
    main2()
  File "client.py", line 22, in main2
    s.send(bytes(sample))
TypeError: 'float' object cannot be interpreted as an integer

假设我必须发送字节,将浮点数转换为字节然后在收到后返回浮点数的最佳方法是什么?

以下是客户端代码:

def main2():
    import socket

    s = socket.socket()
    host = socket.gethostname()  # client and server are on same network
    port = 1247
    s.connect((host, port))
    print(s.recv(1024))
    sample = [0.9,120000,0.85,12.8,0.1,28,16,124565,0.72,3.9]
    s.send(bytes(sample))
    print("the message has been sent")

if __name__ == '__main__':
    main2()

服务器代码,万一重要:

def main2():
    import socket

    s = socket.socket()
    host = socket.gethostname()
    port = 1247
    s.bind((host,port))
    s.listen(5)
    while True:
        try:
            c, addr = s.accept()
            print("Connection accepted from " + repr(addr[1]))
            c.send(bytes("Server approved connection\n", "UTF-8"))
            print(repr(addr[1]) + ": " + str(c.recv(1024)))
            continue
        except (SystemExit, KeyboardInterrupt):
            print("Exiting....")
            c.close()
            break
        except Exception as ex:
            import traceback
            print("Fatal Error...." + str(ex))
            print(traceback.format_exc())
            c.close()
            break

if __name__ == '__main__':
    main2()

1 个答案:

答案 0 :(得分:2)

struct.packstruct.unpack将各种类型的数据打包到字节流中:

>>> import struct
>>> sample = [0.9,120000,0.85,12.8,0.1,28,16,124565,0.72,3.9]
>>> data = struct.pack('<10f',*sample)
>>> print(data)
b'fff?\x00`\xeaG\x9a\x99Y?\xcd\xccLA\xcd\xcc\xcc=\x00\x00\xe0A\x00\x00\x80A\x80J\xf3G\xecQ8?\x9a\x99y@'
>>> data = struct.unpack('<10f',data)
>>> data
(0.8999999761581421, 120000.0, 0.8500000238418579, 12.800000190734863, 0.10000000149011612, 28.0, 16.0, 124565.0, 0.7200000286102295, 3.9000000953674316)

在上面的代码中,<10f表示将十个浮点数(小包)打包(或解包)到字节字符串中。

另一个选择是使用JSON将列表对象序列化为字符串并将其编码为字节字符串:

>>> import json
>>> data = json.dumps(sample).encode()
>>> data # byte string
b'[0.9, 120000, 0.85, 12.8, 0.1, 28, 16, 124565, 0.72, 3.9]'
>>> json.loads(data) # back to list of floats
[0.9, 120000, 0.85, 12.8, 0.1, 28, 16, 124565, 0.72, 3.9]