2011-08-12 68 views
0

我是UDP的新手。使用测试环境,我可以发送/接收单个UDP消息。但是,我试图弄清楚如何接收多个UDP消息。我希望MyListener服务在我发送它们的时候全天接收UDP数据包。我感谢任何帮助。如下所示,如果我在DoSomethingWithThisText的周围放置一段时间(真),那么在调试的时候就可以工作。但是,在尝试将MyListener作为服务运行时,它不起作用,因为Start永远不会超过while(true)循环。UDP在.NET中发送/接收

我的听众服务看起来像这样...

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(); 
} 

回答

1

我结束了使用微软的异步方法,在这里找到 - BeginReceiveEndReceive

像微软建议,我把我的BeginReceive Start方法中是这样的:

UdpState s = new UdpState(); 
s.e = listenerEP; 
s.u = udpListener; 

udpListener.BeginReceive(new AsyncCallback(ReceiveCallback), s); 

然而,让听者继续接收消息,我打电话BeginReceive再次ReceiveCallback函数中,递归。这当然是潜在的内存泄漏,但我在回归测试中还没有遇到问题。

private void ReceiveCallback(IAsyncResult ar) 
{ 
    UdpClient u = (UdpClient)((UdpState)ar.AsyncState).u; 
    IPEndPoint e = (IPEndPoint)((UdpState)ar.AsyncState).e; 

    UdpState s = new UdpState(); 
    s.e = e; 
    s.u = u; 
    udpListener.BeginReceive(new AsyncCallback(ReceiveCallback), s); 

    Byte[] messageBytes = u.EndReceive(ar, ref e); 
    string messageString = Encoding.ASCII.GetString(messageBytes); 

    DoSomethingWithThisText(messageString); 
} 
+1

这里没有资源泄漏,因为您调用了'EndReceive',所有与每个读取操作相关的资源都会被正确清理。请注意,这些天'ReadAsync'可能更可取。 –

2

你应该叫从同时或另一循环中接收。

+0

如果我在我的DoSomethingWithThisText周围添加一个while(true)循环,那会有所帮助,但它只能在Debugger中起作用。如果我尝试将MyListener作为服务运行,则该服务将在启动时超时,因为它永远不会超过while(true)循环。 – WEFX