UDP协议是不可靠的协议,传输速率快
服务器端:
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 UDPServer {class Server{private Socket _ServerSocket; //服务器监听套接字private bool _IsListionContect; //是否在监听public Server(){//定义网络终节点(封装IP和端口)IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),1000);//实例化套接字_ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//服务端绑定地址 _ServerSocket.Bind(endPoint);EndPoint ep = (EndPoint)endPoint;while (true){//准备一个数据缓存byte[] msyArray = new byte[0124 * 0124];//接受客户端发来的请求,返回真实的数据长度int TrueClientMsgLenth = _ServerSocket.ReceiveFrom(msyArray,ref ep);//byte数组转字符串string strMsg = Encoding.UTF8.GetString(msyArray, 0, TrueClientMsgLenth);//显示客户端数据Console.WriteLine("客户端数据:" + strMsg);}}static void Main(string[] args){Server obj = new Server();}} }
客户端:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;using System.Threading; using System.Net; using System.Net.Sockets;namespace UDPClient {class Client{private Socket _ClientSocket; //客户端通讯套接字private IPEndPoint SeverEndPoint; //连接到服务器端IP和端口public Client(){//服务器通信地址SeverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1000);//建立客户端Socket_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);EndPoint ep =(EndPoint) SeverEndPoint;while (true){//输入信息string strMsg = Console.ReadLine();//退出if (strMsg == "exit"){break;}//字节转换Byte[] byeArray = Encoding.UTF8.GetBytes(strMsg);//发送数据 _ClientSocket.SendTo(byeArray,ep);Console.WriteLine("我:" + strMsg);}//关闭连接 _ClientSocket.Shutdown(SocketShutdown.Both);//清理连接资源 _ClientSocket.Close();}static void Main(string[] args){Client obj = new Client();}} }