我是 UDP 新手。使用测试环境,我能够发送/接收单个 UDP 消息。但是,我试图弄清楚如何接收多个 UDP 消息。我希望 MyListener 服务在我发送它们时全天接收 UDP 数据包。我很感激任何帮助。
PS - 如下面的答案所述,如果我在 DoSomethingWithThisText 周围放置一段时间(true),则在调试时将起作用。但是,当尝试将 MyListener 作为服务运行时它不起作用,因为 Start 永远不会超过 while(true) 循环。
我的听众服务看起来像这样......
public class MyListener
{
private udpClient udpListener;
private int udpPort = 51551;
public void Start()
{
udpListener = new UdpClient(udpPort);
IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Any, udpPort);
Byte[] message = udpListener.Receive(ref listenerEndPoint);
Console.WriteLine(Encoding.UTF8.GetString(message));
DoSomethingWithThisText(Encoding.UTF8.GetString(message));
}
}
我的发件人如下所示:
static void Main(string[] args)
{
IPAddress ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
int port = 51551;
//define some variables.
Console.Read();
UdpClient client = new UdpClient();
client.Connect(new System.Net.IPEndPoint(ipAddress, port));
Byte[] message = Encoding.UTF8.GetBytes(string.Format("var1={0}&var2={1}&var3={2}", new string[] { v1, v2, v3 }));
client.Send(message, message.Length);
client.Close();
Console.WriteLine(string.Format("Sent message");
Console.Read();
}