Java 和 C# 之间的 UDP 通信

UDP communication between Java and C#

我正在尝试将 Java 程序与 C# 程序进行通信,但无法正常工作。

代码非常基础,这里是:

这是Java客户

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) {
    }
}

这是 C# 服务器

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);
}

c#服务器是一个Unity文件,我的意思是,我从Unity执行它,所以Start是第一个调用的方法。

我希望他们通过我计算机中的端口 10000(或任何其他端口)进行通信,java 的 main 和 c# 的启动似乎已执行,但从未调用回调。

知道为什么它不起作用吗?谢谢大家

BeginReceive() 是非阻塞的。你的程序在接收到任何东西之前就终止了。使用 Receive() 或在服务器代码末尾放置一个忙等待循环。

我已经解决了,在 Java 客户端中 new DatagramSocket() 必须不带任何参数调用,而在 c# 服务器中 new UdpClient(port);必须仅使用端口调用。