代码之家  ›  专栏  ›  技术社区  ›  JacobIRR

在套接字连接上发送浮点数组

  •  0
  • JacobIRR  · 技术社区  · 6 年前

    我正在测试一个简单的客户机/服务器套接字设置。从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 回复  |  直到 6 年前
        1
  •  2
  •   Mark Tolonen    6 年前

    struct.pack struct.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]