1. 程式人生 > >c# 使用UDPClient實現非同步通訊

c# 使用UDPClient實現非同步通訊

server:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace AsyncServer
{
    class Program
    {
        private static IPEndPoint epServer;
        private static IPEndPoint epClient;
        private static UdpClient server;

        static void Main(string[] args)
        {
            epServer = new IPEndPoint(IPAddress.Any, 11000);    //設定伺服器埠,IP是本程式所在PC的內網IP
            epClient = new IPEndPoint(IPAddress.Any, 0);    //設定客戶端,任意IP,任意埠號
            server = new UdpClient(epServer);   //繫結設定的伺服器埠和IP
            Console.WriteLine("listening...");
            while (true) {
                //下面三行程式碼經過修改,原始碼如下
                //server.BeginReceive(new AsyncCallback(ReceiveCallback), null);
                //該程式碼會被掛起,接收到一個訊息時啟動一個執行緒,該執行緒啟動函式是:ReceiveCallback,在該函式中
                //會修改epClient的值,但程式會繼續向下執行,執行到server.BeginSend時,發現epClient是無效的,報異常
                //所以改為如下程式碼,可以正常執行
                IAsyncResult iar = server.BeginReceive(null, null);
                byte[] receiveData = server.EndReceive(iar, ref epClient);
                Console.WriteLine("Received a message from [{0}]: {1}", epClient, Encoding.ASCII.GetString(receiveData));
                //以下是傳送訊息回客戶端
                string strSend = "hello " + epClient.ToString();
                byte[] sendData = Encoding.ASCII.GetBytes(strSend);
                //下面一行程式碼,將啟動一個執行緒,該執行緒啟動函式:SendCallback,該函式結束掛起的非同步傳送
                server.BeginSend(sendData, sendData.Length, epClient, new AsyncCallback(SendCallback), null);
            }
        }
        //此函式未被使用,如需使用,可以借鑑
        private static void ReceiveCallback(IAsyncResult iar)
        {
            byte[] receiveData = server.EndReceive(iar, ref epClient);
            Console.WriteLine("Received a message from [{0}]: {1}", epClient, Encoding.ASCII.GetString(receiveData));
        }

        private static void SendCallback(IAsyncResult iar)
        {
            int sendCount = server.EndSend(iar);
            if (sendCount == 0)
            { Console.WriteLine("Send a message failure..."); }
        }
    }
}

client
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace AsyncClient
{
    class Program
    {
        private static IPEndPoint epServer;
        private static UdpClient local;

        static void Main(string[] args)
        {
            //設定伺服器端IP和埠
            epServer = new IPEndPoint(IPAddress.Parse("192.168.1.140"), 11000);
            local = new UdpClient(9001);    //繫結本機IP和埠,9001
            while (true) {
                string strSend = Console.ReadLine();
                if (strSend == "exit") break;
                byte[] sendData = Encoding.ASCII.GetBytes(strSend);
                //開始非同步傳送,啟動一個執行緒,該執行緒啟動函式是:SendCallback,該函式中結束掛起的非同步傳送
                local.BeginSend(sendData, sendData.Length, epServer, new AsyncCallback(SendCallback), null);
                //開始非同步接收啟動一個執行緒,該執行緒啟動函式是:ReceiveCallback,該函式中結束掛起的非同步接收
                local.BeginReceive(new AsyncCallback(ReceiveCallback), null);
            }
        }

        private static void SendCallback(IAsyncResult iar)
        {
            int sendCount = local.EndSend(iar);
            if (sendCount == 0)
            { Console.WriteLine("Send a message failure..."); }
        }

        private static void ReceiveCallback(IAsyncResult iar)
        {
            byte[] receiveData = local.EndReceive(iar, ref epServer);
            Console.WriteLine("Server: {0}", Encoding.ASCII.GetString(receiveData));
        }
    }
}