C# : UDP 的訊息傳遞程式

作品

書籍

課程

程式集

小說集

論文集

散文集

影片集

編輯雜誌

程式人

電子書

JavaScript

計算語言學

微積分

Blender 動畫

C# 語言

系統程式

高等 C 語言

Java

Android

Verilog

Wikidot

R 統計軟體

機率統計

計算機數學

組合語言

人工智慧

開放原始碼

網路資源運用

計算機結構

相關訊息

常用工具

友站連結

在家教育

RSS

最新修改

網頁列表

簡體版

English

簡介

使用 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);
        }
    }
}

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License