如果需要查看更多文章,請微信搜索公眾號 csharp編程大全,需要進C#交流群群請加微信z438679770,備注進群, 我邀請你進群! ! !

網路通信協議中的UDP通信是無連接通信,客戶端在發送資料前無需與服務器端建立連接,即使服務器端不在線也可以發送,但是不能保證服務器端可以收到資料,本文實體即為基于C#實作的UDP通信,具體功能代碼如下:
服務器端代碼如下
static void Main(string[] args)
{
UdpClient client = null;
string receiveString = null;
byte[] receiveData = https://www.cnblogs.com/zyr365/p/null;
//實體化一個遠程端點,IP和埠可以隨意指定,等呼叫client.Receive(ref remotePoint)時會將該端點改成真正發送端端點
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
client = new UdpClient(11000);
receiveData = client.Receive(ref remotePoint);//接收資料
receiveString = Encoding.Default.GetString(receiveData);
Console.WriteLine(receiveString);
client.Close();//關閉連接
}
}
客戶端代碼如下:
static void Main(string[] args)
{
string sendString = null;//要發送的字串
byte[] sendData = null;//要發送的位元組陣列
UdpClient client = null;
IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
int remotePort = 11000;
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//實體化一個遠程端點
while (true)
{
sendString = Console.ReadLine();
sendData = https://www.cnblogs.com/zyr365/p/Encoding.Default.GetBytes(sendString);
client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//將資料發送到遠程端點
client.Close();//關閉連接
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/212381.html
標籤:C#
下一篇:C# 佇列(Queue)
