簡體   English   中英

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# 的 start 似乎已執行,但從未調用回調。

為什么它不起作用的任何想法? 謝謝大家。

BeginReceive()是非阻塞的。 您的程序在它可以接收任何東西之前終止。 使用Receive()或在服務器代碼的末尾放置一個忙等待循環。

我已經解決了,在 Java 客戶端 new DatagramSocket() 必須不帶任何參數調用,而在 c# 服務器 new UdpClient(port); 必須僅使用端口調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM