這邊主要的重點是 UdpClient 這個類別,雖然從字面上這個類別叫做 UDP 的 Client (客戶端),但實際上我們也可以用它來建立伺服器,簡單來說 UdpClient 類別可以同時建立 伺服器端 (Server) 與 客戶端 (Client) 兩種功能。
如果今天要建立伺服器端 UdpClient 則要宣告成 UdpClient uc = new UdpClient(5555); ,這裡的 5555 代表伺服器的 Port (監聽埠)。
如果今天要建立客戶端 UdpClient 擇要宣告成 UdpClient uc = new UdpClient(); ,也就是不需要指定 Port,因為只是發送消息,並不是要接收,所以電腦會依流水號的方式分配Port,將資料傳到指定IP:Port上 (此時指定IP:Port是使用 IPEndPoint 類別)。
以下範例程式碼:
伺服器端:
using System;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("這是伺服器...\n");
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 5555);
UdpClient uc = new UdpClient(ipep.Port);
int i = 0;
while (true)
{
Console.WriteLine(System.Text.Encoding.UTF8.GetString(uc.Receive(ref ipep)));
byte[] b = System.Text.Encoding.UTF8.GetBytes("這是'伺服器'回傳的訊息 ~ " + i++);
uc.Send(b, b.Length, ipep);
}
}
}
客戶端:
using System;
using System.Net;
using System.Net.Sockets;
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("這是客戶端...\n");
IPEndPoint ipep = new IPEndPoint (IPAddress.Parse ("127.0.0.1"), 5555);
UdpClient uc = new UdpClient ();
for (int i = 0; i<10; i++) {
byte[] b = System.Text.Encoding.UTF8.GetBytes ("這是'客戶端'傳送的訊息 ~ " + i);
uc.Send (b, b.Length, ipep);
Console.WriteLine (System.Text.Encoding.UTF8.GetString (uc.Receive (ref ipep)));
}
}
}
執行結果:
