摘要:本文使用C#的Socket类简单的实现了通过UDP通信的程序。
示例编写环境
操作系统:Windows 7 32bit Ultimate
开发软件:Microsoft Visual Studio Ultimate 2012 Update 1
程序集: Microsoft .Net Framework 4.5
示例代码
static void Main(string[] args) { string _ip = "10.119.135.247"; int _port = 5000; string command = "<call,1>"; //主机名 Console.WriteLine("Host name is " + Dns.GetHostName()); //设置IP和端口号 IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(_ip), _port); //定义网络类型,数据连接类型和网络协议UDP Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // IPAddress.Any:提供一个 IP 地址,指示服务器应侦听所有网络接口上的客户端活动。此字段为只读。 IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)sender; //对于不存在的IP地址,100毫秒后解除阻塞模式限制 server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100); byte[] data = new byte[1024]; data = Encoding.ASCII.GetBytes(command); // 将字节数据发送到终结点 server.SendTo(data, data.Length, SocketFlags.None, ipep); data = new byte[1024]; int recv = server.ReceiveFrom(data, ref Remote); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); // 持续接收数据知道终止符出现 // 本例中的终止符是“<call,ok>” string info = String.Empty; while (info.ToLower() != "<call,ok>") { recv = server.ReceiveFrom(data, ref Remote); info = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(info); } server.Close(); }
运行结果