2010-11-17 154 views
0

我試圖用C sharp創建一個簡單的UDP應用程序,沒有什麼複雜的,連接,發送一些文本並接收它!但它一直拋出這個異常!C#中的UDP客戶端

「現有連接被遠程主機強制關閉」!

代碼:

 byte[] data = new byte[1024]; 
    IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); 

    Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 

    string welcome = "Hello, are you there?"; 
    data = Encoding.ASCII.GetBytes(welcome); 
    server.SendTo(data, data.Length, SocketFlags.None, ipep); 

    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); 
    EndPoint tmpRemote = (EndPoint)sender; 

    data = new byte[1024]; 
    int recv = server.ReceiveFrom(data, ref tmpRemote); 

    Console.WriteLine("Message received from {0}:", tmpRemote.ToString()); 
    Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); 



    Console.WriteLine("Stopping client"); 
    server.Close(); 

感謝=)

+0

聽起來像服務器偵聽到終點是死亡 – 2010-11-17 17:10:00

回答

0

您是否嘗試過檢查IP地址是有效的,該端口沒有被用於別的東西嗎?

的Windows:

開始>運行> 「cmd」> 「ipconfig」。

+0

是的!同樣的例外! – user511023 2010-11-17 16:45:15

0

請嘗試關閉您的防火牆軟件。

+0

當目標端點爲127.0.0.1時,這有何幫助? – 2010-11-17 18:27:04

+0

它不應該除非他安裝了一些奇怪的第三方防火牆。無論如何,這是要消除的。 – rboarman 2010-11-17 18:49:56

2

在呼叫Receive之前,您應該告訴系統您正在偵聽端口9050上的UDP數據包。 添加server.Bind(ipep);Socket server = new Socket(...);

0

如果你不知道應答服務器的IP,您做的更好: recv = server.Receive(data);

這是我suggetion你的代碼。您可以使用條件(在我的例子是一個無限循環)使用do-while循環:

 byte[] data = new byte[1024]; 
     IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); 

     Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 

     string welcome = "Hello, are you there?"; 
     data = Encoding.ASCII.GetBytes(welcome); 
     server.ReceiveTimeout = 10000; //1second timeout 
     int rslt = server.SendTo(data, data.Length, SocketFlags.None, ipep); 

     data = new byte[1024]; 
     int recv = 0; 
     do 
     { 
      try 
      { 
       Console.WriteLine("Start time: " + DateTime.Now.ToString()); 
       recv = server.Receive(data); //the code will be stoped hier untill the time out is passed 
      } 
      catch { } 
     } while (true); //carefoul! infinite loop! 

     Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); 
     Console.WriteLine("Stopping client"); 
     server.Close();