如何转换Long - > byteArray-> String - > byteArray - > Long over socket?

时间:2017-03-31 00:17:37

标签: java string sockets byte

我想通过套接字发送包含长值的消息。我想发送字符串消息。为了节省字节并使消息更短,我想以8个字符的字符串发送64位长的字节值。以下是我的代码,但我在套接字的另一端收到了错误的值:

这是服务器:

public class ClockSkewServer {
public static void main (String args[]){
    try {
        ServerSocket s = new ServerSocket(3000);
        System.out.println("Server is listening!");
        Socket connection = s.accept();
        connection.setKeepAlive(true);
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        PrintWriter pw = new PrintWriter(connection.getOutputStream(), true);
        while (true) {

            String message = br.readLine(); 
            System.out.println(message);
            Long receivedTime = ByteUtil.stringToLong(message);
            System.out.println(receivedTime);



        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}
    }

这是客户:

public class ClockSkewClient {
public static void main (String args[]) throws UnknownHostException, IOException, InterruptedException{
    Socket s1 = new Socket(args[0], 3000);
    s1.setKeepAlive(true);
    PrintWriter out1 = new PrintWriter(s1.getOutputStream(), true);
    long l = new Long("1490917469228");
    //System.out.println(l);
    while (true){
        Thread.sleep(1000);
        String message  = ByteUtil.longToString(l);
        System.out.println("Client message: " + message);
        System.out.println(ByteUtil.stringToLong(message));
        out1.println(message);
    }

}
}

这是我的字节转换类:

public class ByteUtil {
    private static ByteBuffer longBuffer = ByteBuffer.allocate(Long.BYTES);
    private static ByteBuffer shortBuffer = ByteBuffer.allocate(Short.BYTES);  
    private static ByteBuffer byteBuffer = ByteBuffer.allocate(Byte.BYTES);  

    public static byte[] longToBytes(long x) {
        longBuffer.putLong(0, x);
        return longBuffer.array();
    }

    public static long bytesToLong(byte[] bytes) {
        return ByteBuffer.wrap(bytes).getLong();
    }


    public static String longToString (long x) throws UnsupportedEncodingException{
        return new String (longToBytes(x), "ISO-8859-1");
    }

    public static long stringToLong (String s) throws UnsupportedEncodingException{
        return bytesToLong(s.getBytes("ISO-8859-1"));
    }




}

ByteUtil工作正常,因为客户端可以正确检索原始长值,但是当我通过套接字发送它时会失真。

我在客户端成功获得了长值1490917469228,但在服务器端我获得了1490911439916.

我知道我们可以发送字节并避免这个问题,但由于某种原因,我坚持要通过套接字发送字符串。

由于

1 个答案:

答案 0 :(得分:3)

  

我想通过套接字发送包含长值的消息。我想发送字符串消息。为了节省字节并使消息更短,我想以8个字符的字符串发送64位长的字节值。

为什么呢?将64位作为8个字符发送可能需要 16 个字节。 128位。它当然不会保存任何字节,所有这些转换只会浪费时间和代码空间:特别是开发时间,特别是当您的代码不起作用时。

只需使用double quantity = double.Parse(txtQuantity.Text); lblConversion.Text = string.Format("{0} {1} = {2} {3}", quantity, currenFrom, iRate * quantity, currencyTo); DataOutputStream.writeLong()即可。

相关问题