发送和接收包含double的DatagramPacket

时间:2014-02-14 03:07:04

标签: java sockets udp byte datagram

我想要做的是1)在客户端,将double(当前为1.75)转换为bytes[]并使用DatagramPacket将其发送到服务器; 2)在服务器端,接收请求,获取bytes[]数据,将其转换为double并打印出来。

UDPClient.java:

import java.net.*;
import java.io.*;
import java.nio.ByteBuffer;

public class UDPClient {

    private static byte[] doubleToByteArray(double x) {
        byte[] bytes = new byte[8];
        ByteBuffer.wrap(bytes).putDouble(x);
        return bytes;
    }

    public static void main(String args[]) {
        DatagramSocket aSocket = null;
        try {
            aSocket = new DatagramSocket();
            byte[] m = doubleToByteArray(1.75);
            InetAddress aHost = InetAddress.getByName("localhost");
            int serverPort = 6789;
            DatagramPacket request
                    = new DatagramPacket(m, m.length, aHost, serverPort);
            aSocket.send(request);
        } catch (SocketException e) {
            System.out.println("Socket: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO: " + e.getMessage());
        } finally {
            if (aSocket != null) {
                aSocket.close();
            }
        }
    }
}

UDPServer.java:

import java.net.*;
import java.io.*;
import java.nio.ByteBuffer;

public class UDPServer {

    private static double byteArrayToDouble(byte[] bytes) {
        double d = 0.0;
        ByteBuffer.wrap(bytes).putDouble(d);
        return d;
    }

    public static void main(String args[]) {
        DatagramSocket aSocket = null;
        try {
            aSocket = new DatagramSocket(6789);
            // create socket at agreed port
            byte[] buffer = new byte[1000];
            while (true) {
                DatagramPacket request = new DatagramPacket(buffer, buffer.length);
                aSocket.receive(request);
                System.out.println(new String(request.getData(), 0, request.getLength()));
                // output: some messy characters
                System.out.println(byteArrayToDouble(request.getData()));
                // output: "0.0" (of course, unfortunately)
            }
        } catch (SocketException e) {
            System.out.println("Socket: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO: " + e.getMessage());
        } finally {
            if (aSocket != null) {
                aSocket.close();
            }
        }
    }
}

我应该如何修改发送/接收机制以便传输正确的字节?

1 个答案:

答案 0 :(得分:1)

private static double byteArrayToDouble(byte[] bytes) {
        double d = 0.0;
        ByteBuffer.wrap(bytes).putDouble(d);
        return d;
    }

将字节数组转换为double是一种奇怪的方法。它没有对双重做任何事情。它不能。 Java中没有参考参数。它应该是 get 。基本上整个方法可以替换为:

ByteBuffer.wrap(request.getData(), 0, request.getLength()).getDouble().

E&安培; OE