C#datagramsocket无法接收

时间:2016-12-21 08:19:31

标签: c# udp

我试图让UWP上的datagramsocket连接到桌面上的UDPClient。

奇怪的是,datagramsocket从不接收来自UDPClient的任何消息(事件不起作用),除非首先从datagramsocket向UDPClient发送消息。

另一方面,我确定我的配置(IP / PORT设置)没问题,因为UDPClients上的相同配置工作正常。

我的代码有什么问题吗?(UWP代码:)

private async void btn_start_Click(object sender, RoutedEventArgs e)//Listen
{
    hostname = new HostName("192.168.1.5");
    remotename = new HostName("192.168.1.5");

    datagramsocket = new DatagramSocket();

    datagramsocket.MessageReceived += Datagramsocket_MessageReceived;

    try
    {
        await datagramsocket.BindServiceNameAsync("8010");

        await datagramsocket.ConnectAsync(remotename, "8009");
    }
    catch(Exception err)
    {
        //show err message method
    }
}

private async void Datagramsocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{//read from args
    //it works after click send button
}

//if i don't click btn_send first, then the MessageReceived event will never work
private async void btn_send_Click(object sender, RoutedEventArgs e)//send
{
    string str_send = tb_send.Text;
    byte[] str_byte = Encoding.Unicode.GetBytes(str_send);

    IOutputStream outputstream = await datagramsocket.GetOutputStreamAsync(remotename, "8009");

    DataWriter writer = new DataWriter(outputstream);
    writer.WriteBytes(str_byte); 
    await writer.StoreAsync();
}

0 个答案:

没有答案