close
UDP 的訊息傳遞程式

簡介

使用 UDP 方式傳送訊息,由於封包是以一個一個的方式分別傳輸,先傳送者不一定會先到,甚至於沒有到達也不進行處理。由於這種方式不是連線導向的方式,因此不需要記住連線的 Socket,只要直接用 Socket 當中的 ReceiveFrom(data, ref Remote) 函數即可。

程式範例

以下是一個 UDP 客戶端 UdpClient,該客戶端會接受使用者的輸入,然後將訊息傳遞給伺服端的 UdpServer。

檔案:UdpClient.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpClient
{
    public static void Main(string[] args)
    {
        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(args[0]), 5555);
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        while(true)
        {
         string input = Console.ReadLine();
         if (input == "exit")
         break;
         server.SendTo(Encoding.ASCII.GetBytes(input), ipep);
        }
        Console.WriteLine("Stopping client");
        server.Close();
    }
}
	

以下是一個 Udp 的伺服端,利用無窮迴圈接收上述客戶端傳來的訊息,然後列印在螢幕上。

檔案:UdpServer.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpServer
{
    public static void Main()
    {
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 5555);
        Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        newsock.Bind(ipep);
        Console.WriteLine("Waiting for a client...");
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
        EndPoint Remote = (EndPoint)(sender);
        while(true)
        {
         byte[] data = new byte[1024];
         int recv = newsock.ReceiveFrom(data, ref Remote);
         Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
//     newsock.SendTo(data, recv, SocketFlags.None, Remote);
        }
    }
}
	

陳鍾誠 (2010年06月15日),(網頁標題) C# : UDP 的訊息傳遞程式,(網站標題) 免費電子書:C# 程式設計,2010年06月15日,取自 http://cs0.wikidot.com/udpclientserver1 ,網頁修改第 0 版。

arrow
arrow

    Johnson峰 發表在 痞客邦 留言(0) 人氣()