我用DatagramSocket编写了一个测试程序来接收数据。但收到5或6包后,这是不会收到更多的数据包!
有人有解决方案吗?
我的测试代码是:
public MainPage()
{
this.InitializeComponent();
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
Listen();
}
private async void Listen()
{
try
{
Windows.Networking.Sockets.DatagramSocket socket = new Windows.Networking.Sockets.DatagramSocket();
socket.MessageReceived += Socket_MessageReceived;
//You can use any port that is not currently in use already on the machine.
string serverPort = "1337";
//Bind the socket to the serverPort so that we can start listening for UDP messages from the UDP echo client.
await socket.BindServiceNameAsync(serverPort);
}
catch (Exception e)
{
//Handle exception.
}
}
public async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
{
//Read the message that was received from the UDP echo client.
Stream streamIn = args.GetDataStream().AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
string message = await reader.ReadLineAsync();
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
Alpha.Text = message;
}
);
}
我已经通过wireshark跟踪检查我是否正在接收数据,但是在我的visual studio解决方案中它无法正常工作。
答案 0 :(得分:1)
我使用了Control.InboundBufferSizeInBytes,然后它可以正常工作!
listener = new DatagramSocket();
listener.MessageReceived += MessageReceived;
listener.Control.InboundBufferSizeInBytes = 1;
await listener.BindServiceNameAsync("1337");
答案 1 :(得分:1)
这是因为它恰好是您打开UDP侦听器的另一个实例,或者您在错误的位置初始化!