【问题标题】:send array of floats over a socket connection通过套接字连接发送浮点数组
【发布时间】:2018-05-23 18:15:52
【问题描述】:

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

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()

【问题讨论】:

  • “最佳”在什么意义上?这里需要权衡取舍(速度、准确性、复杂性、比特率)。
  • 速度在我的情况下

标签: python python-3.x sockets


【解决方案1】:

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)

在上面的代码中,&lt;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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 2019-03-15
    • 2015-12-08
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2010-12-10
    • 2021-12-20
    相关资源
    最近更新 更多