VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之c#实现简单控制台udp异步通信程序示例

实现客户端发送请求,服务器端响应机制

UDP客户端代码

复制代码 代码如下:

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

 

namespace Client
{
    class Program
    {
        //客户端 Socket对象
        private static Socket clientSocket;
        //服务器端 终点
        private static EndPoint epServer;
        //接收数据的字符数组
        private static byte[] receiveData;

        public static void Main(string[] args)
        {
            //客户端Socket对象实例化
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //设置服务器端IP地址和对应端口
            IPEndPoint server = new IPEndPoint(IPAddress.Parse("192.168.1.165"), 11000);
            //实例化服务器端 终点
            epServer = (EndPoint)server;
            string msg;     //要发送的消息
            byte[] sendData;    //要发送的字符串
            while (true) {
                msg = Console.ReadLine();   //输入要发送的消息
                if (msg == "exit") break;   //当输入“exit”时,退出客户端程序
                //将消息通过ASCII编码转换为字符数组,
                //如果要发送汉字或其他特殊符号,可以采用UTF-8
                sendData = Encoding.ASCII.GetBytes(msg);   
                //开始异步发送消息
                //参数:sendData           要发送的数据
                //参数:0:                 要发送数据的起始位置
                //参数:sendData.Length:   要发送数据的字节数
                //参数:SocketFlags.None:  按位组合方式
                //参数:epServer:          接收方设备(包含IP和端口)
                //参数:new AsyncCallback(SendData):   委托
                //参数:null:          请求的状态信息
                clientSocket.BeginSendTo(sendData, 0, sendData.Length, SocketFlags.None,
                    epServer, new AsyncCallback(SendData), null);
                //实例化接收数据的字符数组
                //若在声明时已经初始化,此处依然要进行重新初始化
                //当上次接收的数据长度大于本次,则该数组里包含上次接收的残留数据
                //比如:上次接收“你个小逗逼”。本次接收“开玩笑”。
                //则数组中的数据为:“开玩笑逗逼”。
                receiveData = new byte[1024];
                //开始异步接收消息
                //参数部分与异步发送部分对应,基本一致
                clientSocket.BeginReceiveFrom(receiveData, 0, receiveData.Length, SocketFlags.None,
                    ref epServer, new AsyncCallback(ReceiveData), null);
            }
        }

        //异步发送消息的委托函数
        private static void SendData(IAsyncResult iar)
        {
            //完成异步发送
            clientSocket.EndSend(iar);
        }

        //异步接收消息的委托函数
        private static void ReceiveData(IAsyncResult iar)
        {
            //完成异步接收  recv 表示接收到的字节数
            int recv = clientSocket.EndReceive(iar);
            //将接收到的数据打印出来
            Console.WriteLine("Server: " + Encoding.ASCII.GetString(receiveData, 0, recv));
        }

    }
}

 

UDP服务器端代码

 

复制代码 代码如下:

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

 

namespace Server
{
    class AsyncUdpServer
    {
        //服务器端Socket对象
        private static Socket serverSocket;
        //接收数据的字符数组
        private static byte[] receiveData = new byte[1024];

        public static void Main(string[] args)
        {
            //实例化服务器端Socket对象
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //服务器端的IP和端口,IPAddress.Any实际是:0.0.0.0,表示任意,基本上表示本机IP
            IPEndPoint server = new IPEndPoint(IPAddress.Any, 11000);
            //Socket对象跟服务器端的IP和端口绑定
            serverSocket.Bind(server);
            //客户端的IP和端口,端口 0 表示任意端口
            IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);
            //实例化客户端 终点
            EndPoint epSender = (EndPoint)clients;
            //开始异步接收消息  接收后,epSender存储的是发送方的IP和端口
            serverSocket.BeginReceiveFrom(receiveData, 0, receiveData.Length, SocketFlags.None,
                ref epSender, new AsyncCallback(ReceiveData), epSender);
            Console.WriteLine("Listening...");
            Console.ReadLine();
        }

        private static void SendData(IAsyncResult iar)
        {
            serverSocket.EndSend(iar);
        }

        private static void ReceiveData(IAsyncResult iar)
        {
            //客户端的IP和端口,端口 0 表示任意端口
            IPEndPoint client = new IPEndPoint(IPAddress.Any, 0);
            //实例化客户端 终点
            EndPoint epSender = (EndPoint)client;
            //结束异步接收消息  recv 表示接收到的字符数
            int recv = serverSocket.EndReceiveFrom(iar, ref epSender);           
            //将接收到的数据打印出来,发送方采用什么编码方式,此处就采用什么编码方式 转换成字符串
            Console.WriteLine("Client:" + Encoding.ASCII.GetString(receiveData, 0, recv));
            //定义要发送回客户端的消息,采用ASCII编码,
            //如果要发送汉字或其他特殊符号,可以采用UTF-8           
            byte[] sendData = Encoding.ASCII.GetBytes("hello");
            //开始异步发送消息  epSender是上次接收消息时的客户端IP和端口信息
            serverSocket.BeginSendTo(sendData, 0, sendData.Length, SocketFlags.None,
                epSender, new AsyncCallback(SendData), epSender);
            //重新实例化接收数据字节数组
            receiveData = new byte[1024];
            //开始异步接收消息,此处的委托函数是这个函数本身,递归
            serverSocket.BeginReceiveFrom(receiveData, 0, receiveData.Length, SocketFlags.None,
                ref epSender, new AsyncCallback(ReceiveData), epSender);
        }

    }
}



相关教程