【问题标题】:UDP communication between Java and C#Java和C#之间的UDP通信
【发布时间】:2016-09-02 14:09:57
【问题描述】:

我正在尝试将 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 似乎已执行,但从未调用回调。

关于它为什么不起作用的任何想法?谢谢大家。

【问题讨论】:

  • 我也尝试在 c# 中使用阻塞接收,但从未收到消息。所以问题可能出在连接上,但我找不到。

标签: java c# udp communication


【解决方案1】:

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

【讨论】:

  • 我尝试过使用 while(true){},但随后 Unity 被阻止。我认为那是因为 Start 方法永远不会结束。
【解决方案2】:

我已经解决了,在 Java 客户端中 new DatagramSocket() 必须在没有任何参数的情况下调用,而在 c# 服务器中 new UdpClient(port);只能使用端口调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    相关资源
    最近更新 更多