C#UDP通讯编程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Configuration;
using System.Threading;
namespace VPNBuild
{
    public class Server
    {
        #region 配置文件字段
        private int backlog = 10;
        private int point;
        #endregion
        #region 字段
        private IPAddress ip;
        private IPEndPoint endpoint;
        UdpClient client;
        #endregion
        #region 服务端线程及状态控制
        private Thread ServerThread;
        private volatile bool IsCouldShutUp = false;
        #endregion
        private long count = 0;
        #region 收发数据部分
        //private ThreadPool pool;
        #endregion

        public Server()
        {
            string hostname = Dns.GetHostName();
            IPAddress[] addresslist = Dns.GetHostAddresses(hostname);
            foreach (IPAddress i in addresslist)
            {
                if (i.AddressFamily == AddressFamily.InterNetwork)
                    ip = i;
            }
            try
            {
                point = Convert.ToInt32(ConfigurationManager.AppSettings["ServerPoint"]);
                endpoint = new IPEndPoint(ip, point);               
            }
            catch
            {
                
            }
        }


        #region 服务端线程启动,关闭;
        public void Start()
        {
            ServerThread = new Thread(new ThreadStart(ServerDealing));
            ServerThread.Start();
        }
        private void ServerDealing()
        {
            client = new UdpClient(endpoint);
            while (!IsCouldShutUp)
            {
                IPEndPoint IP = new IPEndPoint(IPAddress.Any,0);
                Dealing(IP);
                Thread.Sleep(10);
            }
        }
        public void Close()
        {
            IsCouldShutUp = true;
            if (ServerThread != null)
                ServerThread.Abort();
            
        }
        #endregion

        #region 数据处理部分,采用线程池
        private void Dealing(object o)
        {
            IPEndPoint IP = o as IPEndPoint;

            byte[] sendBuffer = new byte[]{0x68,  0x08,  0x00,  0x68,  0x00,  0x80,  0x80,  0x16 };
            sendBuffer[0] = (byte)count;
            byte[] recBuffer = new byte[1024];
            //client.BeginReceive(recBuffer,SocketFlags.None,
            
            recBuffer = client.Receive(ref IP);//接收报文
            string str = "";
            for (int i = 0; i < recBuffer.Length; i++)
            {
                str += Convert.ToString(i,16).PadLeft(2,'0')+" ";
            }
            
            Console.WriteLine(str+DateTime.Now.ToString("yyyyMMdd,hh:mm:ss:ffff")+",次数:"+count);
            count++;
            client.Connect(IP);
            client.Send(sendBuffer,sendBuffer.Length);//应答报文
        }
        #endregion

    }
}

总结:以上程序为udp通讯中服务端,工作模式为,捕捉连接-接收客户报文-建立连接-发送到客户报文。改程序可以稳定运行。有更好的方式,还请联系我。谢谢。

猜你喜欢

转载自my.oschina.net/u/2551141/blog/892212