UDP communication between Java and C#

Tags: , , ,



I’m trying to communicate a Java program with a C# one but it’s not working.

The code is really basic, here it is:

This is the Java client

static InetAddress ip;
static int port = 10000;

public static void main(String args[]) {
    try {
        ip = InetAddress.getByName("127.0.0.1");
        DatagramSocket socket = new DatagramSocket(port, ip);
        byte[] sendData = new byte[1024];
        sendData = "Hola".getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
        socket.send(sendPacket);
        socket.close();
    } catch (Exception e) {
    }
}

And here it is the C# server

static UdpClient client;
static IPEndPoint sender;
void Start () {
    byte[] data = new byte[1024];
    string ip = "127.0.0.1";
    int port =  10000;
    client = new UdpClient(ip, port);       
    sender = new IPEndPoint(IPAddress.Parse(ip), port);

    client.BeginReceive (new AsyncCallback(recibir), sender);

}

static void recibir(IAsyncResult res){
    byte[] bResp = client.EndReceive(res, ref sender);

    //Convert the data to a string
    string mes = Encoding.UTF8.GetString(bResp);

    //Display the string
    Debug.Log(mes);
}

The c# server is a Unity file, I mean, I execute it from Unity, so Start is the first method called.

I would like them to communicate through port 10000 (or any ohter one) in my computer, java’s main and c#’s start seem to be executed but the callback is never called.

Any ideas of why it isn’t working? Thank you all.

Answer

I’ve solved it, in the Java client new DatagramSocket() must be called without any argument, and in the c# server new UdpClient(port); must be called only with the port.



Source: stackoverflow