python无法从网络打印解压缩的浮动

时间:2013-03-28 20:41:04

标签: java python sockets

我尝试从UDP数据报中获取浮点数并打印它们以验证:

import socket
from struct import *

socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket.bind( ('127.0.0.1', 2416) )
msg = bytearray( 4*1024 ) 
f1 = 0.0
f2 = 0.0
f3 = 0.0
while True:
    nBytes = socket.recv_into( msg )
    print( '%d bytes received' % nBytes )
    (f1) = unpack_from( '!f', msg, 0 )
    (f2) = unpack_from( '!f', msg, 4 )
    (f3) = unpack_from( '!f', msg, 8 )
    print( '%f, %f, %f received' % ( f1, f2, f3 ))

引发以下错误:

$ python Server.py
12 bytes received
Traceback (most recent call last):
  File "Server.py", line 13, in <module>
    print( '%f, %f, %f received' % ( f1, f2, f3 ))
TypeError: a float is required

预期输出为1.2, 3.4, 5.6 received

上下文:

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32

有关Java UDP发送方(客户端)的信息:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;

public class Client {

   public static void main( String[] args ) throws Exception {
      try( DatagramSocket clientSocket = new DatagramSocket()) {
         InetAddress target = InetAddress.getByName( "localhost" );
         ByteBuffer msg = ByteBuffer.allocate( 4*1024 );
         for(;;) {
            msg.clear();
            msg.putFloat(   1.20f );
            msg.putFloat(   3.40f );
            msg.putFloat(   5.60f );
            msg.putDouble(  7.80  );
            msg.putDouble(  9.10  );
            msg.putDouble( 11.120 );
            msg.flip();
            clientSocket.send(
               new DatagramPacket( msg.array(), msg.limit(), target, 2416 ));
            Thread.sleep( 2000 );
         }
      }
   }
}

2 个答案:

答案 0 :(得分:2)

这一行是问题所在:

(f1) = unpack_from( '!f', msg, 0 )

尝试

(f1,) = unpack_from( '!f', msg, 0 )

请注意其他逗号。同样地,对于其他两行。

正如您所提到的,unpack_from会返回一个元组。 (f1)不是元组,它是单个值。 (f1,)是一个包含一个元素的元组。

答案 1 :(得分:0)

这个程序效果很好:

import socket
from struct import *

socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket.bind( ('127.0.0.1', 2416) )
msg = bytearray( 4*1024 )
while True:
    nBytes = socket.recv_into( msg )
    print( '%d bytes received' % nBytes )
    (f1,) = unpack_from( '!f', msg,  0 )
    (f2,) = unpack_from( '!f', msg,  4 )
    (f3,) = unpack_from( '!f', msg,  8 )
    (d1,) = unpack_from( '!d', msg, 12 )
    (d2,) = unpack_from( '!d', msg, 20 )
    (d3,) = unpack_from( '!d', msg, 28 )
    print( f1, f2, f3, d1, d2, d3 )
    print( type(f1), type(d1))

并打印:

$ python Server.py
36 bytes received
1.2000000476837158 3.4000000953674316 5.599999904632568 7.8 9.1 11.12
<class 'float'> <class 'float'>
36 bytes received
1.2000000476837158 3.4000000953674316 5.599999904632568 7.8 9.1 11.12
<class 'float'> <class 'float'>
36 bytes received
1.2000000476837158 3.4000000953674316 5.599999904632568 7.8 9.1 11.12
<class 'float'> <class 'float'>