簡體   English   中英

C#中的UDP客戶端

[英]UDP client in C#

我正在嘗試使用C Sharp編寫簡單的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();

謝謝=)

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

您是否嘗試檢查IP地址是否有效以及該端口未用於其他內容?

視窗:

開始>運行>“ cmd ”>“ ipconfig ”。

嘗試關閉防火牆軟件。

如果您不知道應答服務器的IP,則最好執行以下操作: recv = server.Receive(data);

這是我對您代碼的建議。 您可以使用條件式的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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM