C#和Java如何为流转换字节

时间:2015-04-20 13:45:13

标签: java c# sockets byte

我很少尝试将数据从C#UDP服务器发送到Java客户端而没有运气。我知道Java和C#中的字节之间存在差异,但是不完全了解如何实现它。任何帮助都会很棒。

以下是我的C#代码:

TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
int secondsSinceEpoch = (int)t.TotalSeconds;
{
    byte[] data = new byte[1024];

    IPAddress UDP_local_add = IPAddress.Parse("127.0.0.1");

    IPEndPoint endpoint = new IPEndPoint(UDP_local_add, 37);

    UdpClient UDPSocket = new UdpClient(endpoint);




    Console.WriteLine("UDP Server awaiting connections...");

    IPEndPoint sender = new IPEndPoint(UDP_local_add, 0);



    data = UDPSocket.Receive(ref sender);

    Console.WriteLine("Message received from {0}:", sender.ToString());
    Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));

    data =System.Text.Encoding.ASCII.GetBytes(secondsSinceEpoch.ToString());

    Console.WriteLine(secondsSinceEpoch);
    int converted = DecodeInt32(data);
    Console.WriteLine(converted);



    UDPSocket.Send(data, data.Length, sender);


    UDPSocket.Close();

}

及以下是Java客户端代码:

public class TimeUDPClient {
private static final int PORT_TIME = 37;
private static final String QUERY = "Ktora godzina?";
private static final int LINELEN = 5;
private static final long UNIXEPOCH = 2208988800L;

public static void main(String[] args) {
    try {
        byte[] buffer = new byte[LINELEN];
        DatagramSocket sock = new DatagramSocket();
        DatagramPacket dp = new DatagramPacket(QUERY.getBytes(), 0,
                QUERY.length(), InetAddress.getByName(args[0]), PORT_TIME);
        sock.send(dp);
        dp = new DatagramPacket(buffer, LINELEN);
        sock.receive(dp);
        long time = 0;
        int i;
        for (i = 0; i < 4; i++) {
            time *= 256;
            time += (buffer[i] & 255);
        }
        time -= UNIXEPOCH;
        time *= 1000;
        Date d = new Date(time);
        System.out.println(d);
        sock.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

0 个答案:

没有答案