我试图让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();
}