程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 建立UDP服務器並接收客戶端數據

C# 建立UDP服務器並接收客戶端數據

編輯:C#入門知識

C# 建立UDP服務器並接收客戶端數據





服務器端對象類庫:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
namespace UdpChatExample
{
    /// 
    /// UDP服務器對象
    /// 
    public class UDPServerClass
    {
        public delegate void MessageHandler(string Message);//定義委托事件
        public event MessageHandler MessageArrived;
        public UDPServerClass()
        {
            //獲取本機可用IP地址
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ipa in ips)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                {
                    MyIPAddress = ipa;//獲取本地IP地址
                    break;
                }
            }
            Note_StringBuilder = new StringBuilder();
            PortName = 8080;

        }

        public UdpClient ReceiveUdpClient;

        /// 
        /// 偵聽端口名稱
        /// 
        public int PortName;

        /// 
        /// 本地地址
        /// 
        public IPEndPoint LocalIPEndPoint;

        /// 
        /// 日志記錄
        /// 
        public StringBuilder Note_StringBuilder;
        /// 
        /// 本地IP地址
        /// 
        public IPAddress MyIPAddress;

        public void Thread_Listen()
        {
            //創建一個線程接收遠程主機發來的信息
            Thread myThread = new Thread(ReceiveData);
            myThread.IsBackground = true;
            myThread.Start();
        }
        /// 
        /// 接收數據
        /// 
        private void ReceiveData()
        {
            IPEndPoint local = new IPEndPoint(MyIPAddress, PortName);
            ReceiveUdpClient = new UdpClient(local);
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                try
                {
                    //關閉udpClient 時此句會產生異常
                    byte[] receiveBytes = ReceiveUdpClient.Receive(ref remote);
                    string receiveMessage = Encoding.Default.GetString(receiveBytes, 0, receiveBytes.Length);
                    //  receiveMessage = ASCIIEncoding.ASCII.GetString(receiveBytes, 0, receiveBytes.Length);
                    MessageArrived(string.Format("{0}來自{1}:{2}", DateTime.Now.ToString(), remote, receiveMessage));
                    //try
                    //{
                    //    Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
                    //    ReceiveUdpClient.Send(sendBytes, sendBytes.Length, local);
                    //}
                    //catch (Exception e)
                    //{
                    //}
                    //break;

                }
                catch
                {
                    break;
                }
            }
        }

        /// 
        /// 添加日志信息到Note_StringBuilder
        /// 
        public void AddMessage_Note_StringBuilder()
        {

        }
    }
}


界面簡單代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace UdpChatExample
{
    public partial class UDPServerForm : Form
    {
        public UDPServerForm()
        {
            InitializeComponent();
        }
        public delegate void DelegateChangeText(string Messages);
        void ChangeTxt(string Messages)
        {
            string SBText = SB.ToString();
            SB.Remove(0, SB.Length);
            SB.Append(Messages + "\r\n" + SBText);
            richTextBox1.Text = SB.ToString();
        }
        StringBuilder SB = new StringBuilder();
        private void UDPServerForm_Load(object sender, EventArgs e)
        {

        }

        UDPServerClass UDPServerClass1;
        private void button1_Click(object sender, EventArgs e)
        {
            UDPServerClass1 = new UDPServerClass();
            UDPServerClass1.Thread_Listen();
            UDPServerClass1.MessageArrived += new UDPServerClass.MessageHandler(UDPServerClass1_MessageArrived);
        }

        void UDPServerClass1_MessageArrived(string Message)
        {
            richTextBox1 .Invoke (new DelegateChangeText(ChangeTxt),Message);
        } 

        private void UDPServerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(System.Environment.ExitCode);
        }
    }
}









  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved