1. 程式人生 > 程式設計 >C#中使用UDP通訊的示例

C#中使用UDP通訊的示例

網路通訊協議中的UDP通訊是無連線通訊,客戶端在傳送資料前無需與伺服器端建立連線,即使伺服器端不線上也可以傳送,但是不能保證伺服器端可以收到資料。本文例項即為基於C#實現的UDP通訊。具體功能程式碼如下:

伺服器端程式碼如下

static void Main(string[] args)
{
UdpClient client = null;
string receiveString = null;
byte[] receiveData = 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 = Encoding.Default.GetBytes(sendString);

client = new UdpClient();
client.Send(sendData,sendData.Length,remotePoint);//將資料傳送到遠端端點
client.Close();//關閉連線
}

C#中使用UDP通訊的示例

以上就是C#中使用UDP通訊的示例的詳細內容,更多關於c# udp通訊的資料請關注我們其它相關文章!