UDP不属于面向连接的通信,在选择使用协议的时候,选择UDP必须要谨慎。在网络质量令人十分不满意的环境下,UDP协议数据包丢失会比较严重。但是由于UDP的特性:它不属于连接型协议,因而具有资源消耗小,处理速度快的优点,所以通常音频、视频和普通数据在传送时使用UDP较多,因为它们即使偶尔丢失一两个数据包,也不会对接收结果产生太大影响。比如我们聊天用的ICQ和QQ就是使用的UDP协议。我们通过UDP进行信息收发的时候,没有严格客户端和服务端的区别,它不同于UDP,UDP 必须建立可靠连接之后才可以通信,而UDP随时都可以给指定的ip和端口所对应进程发送消息。UDP发送消息时需要绑定自己IP 和 端口号,接收消息的时候没有特殊限制,只要有人给自己发送,自己在线,就可以接收。
服务端程序:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net.Sockets;using System.Net;using System.Threading;namespace UDP_Server{ class Program { static Socket server; static void Main(string[] args) { server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); server.Bind(new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6001));//绑定端口号和IP Console.WriteLine("服务端已经开启"); Thread t = new Thread(ReciveMsg);//开启接收消息线程 t.Start(); Thread t2 = new Thread(sendMsg);//开启发送消息线程 t2.Start(); } ////// 向特定ip的主机的端口发送数据报 /// static void sendMsg() { EndPoint point = new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6000); while (true) { string msg = Console.ReadLine(); server.SendTo(Encoding.UTF8.GetBytes(msg), point); } } ////// 接收发送给本机ip对应端口号的数据报 /// static void ReciveMsg() { while (true) { EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号 byte[] buffer = new byte[1024]; int length = server.ReceiveFrom(buffer, ref point);//接收数据报 string message = Encoding.UTF8.GetString(buffer,0,length); Console.WriteLine(point.ToString()+ message); } } }}
客户端程序
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net;using System.Net.Sockets;using System.Threading;namespace UDP_client{ class Program { static Socket client; static void Main(string[] args) { client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); client.Bind(new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6000)); Thread t = new Thread(sendMsg); t.Start(); Thread t2 = new Thread(ReciveMsg); t2.Start(); Console.WriteLine("客户端已经开启"); } ////// 向特定ip的主机的端口发送数据报 /// static void sendMsg() { EndPoint point = new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6001); while(true){ string msg = Console.ReadLine(); client.SendTo(Encoding.UTF8.GetBytes(msg), point); } } ////// 接收发送给本机ip对应端口号的数据报 /// static void ReciveMsg() { while (true) { EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号 byte[] buffer = new byte[1024]; int length = client.ReceiveFrom(buffer, ref point);//接收数据报 string message = Encoding.UTF8.GetString(buffer, 0, length); Console.WriteLine(point.ToString() + message); } } }}
来源:http://blog.csdn.net/u011484013/article/details/51131267