C#的UDP服务器

最新优化版本

/*
http://www.cnblogs.com/zengqinglei/archive/2013/04/27/3046119.html
*/
using System;
using System.Text;
#region 命名空间
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Media;
#endregion

namespace SocketServerConsole
{
    class Program
    {
        #region 控制台主函数
        /// <summary>
        /// 控制台主函数
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            UdpServer(new IPEndPoint(0, 9167));
        }
        #endregion

        #region Udp连接方式
        /// <summary>
        /// Udp连接方式
        /// </summary>
        /// <param name="serverIP"></param>
        public static void UdpServer(IPEndPoint serverIP)
        {
            SoundPlayer sp = new SoundPlayer();
            bool thread_flag = true;
            Console.WriteLine("UDP服务器开始监听" + serverIP.Port + "端口");
            Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpServer.Bind(serverIP);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)ipep;
            new Thread(() =>
            {
                while (thread_flag)
                {
                    byte[] data = new byte[1024];
                    int length = 0;
                    try
                    {
                        length = udpServer.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                    }
                    string datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    string message = Encoding.UTF8.GetString(data, 0, length);
                    string ipport = (Remote as IPEndPoint).Address.ToString() + ":" + (Remote as IPEndPoint).Port.ToString();
                    Console.WriteLine(string.Format("{0} 收到來自{1}的消息:{2}", datetime, ipport, message));
                    sp.SoundLocation = Thread.GetDomain().BaseDirectory + message;
                    try
                    {
                        sp.PlayLooping();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("Error: {0}, Path={1}", ex.Message, sp.SoundLocation));
                    }

                }
                udpServer.Close();
            }).Start();
            Console.WriteLine("\n\n按[F4]键退出。");
            ConsoleKey key;
            while (true)
            {
                key = Console.ReadKey(true).Key;
                if (key == ConsoleKey.F4)
                {
                    Console.WriteLine("end waiting for udp data.");
                    thread_flag = false;
                    break;
                }
            }
        }
        #endregion
    }
}