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