我尝试从 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 );
}
}
}
}