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(); } } }