C#的UDP服务器
2016-04-02 02:27
471 查看
最新优化版本
/* 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 } }
相关文章推荐
- C#课后题+上机(四)
- C#-get/set和方法重载
- C#里,输入任何几个学生的成绩,用冒泡排序实现从小到排序。
- c#-随机数2
- c#之datagridview格式
- C# 调用c库
- 浅谈C#委托和事件
- C# 反射机制
- C# 面向对象,字符串中取数组
- C# 统计字符串数字个数并输出
- C#第四次上机
- 2016-4-1--C#委托delegate
- c#类的初使用
- C#--冒泡排序
- C#第四章3.(1)
- C# 上机题 写一个静态方法,输出字符串中大小写字母、数字和其他字符个数
- c#-输出参数
- C#学习(9):通过反射设置泛型类型的属性及值
- C#大文件读取和查询--内存映射
- C#中axWindowsMediaPlayer控件的用法