UDP實現一個簡易的聊天室 (Unity&&C#完成)

来源:https://www.cnblogs.com/ASsss/archive/2019/02/27/10446364.html
-Advertisement-
Play Games

效果展示(尚未完善) using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Threading; using System.Net; using System.Net.S ...


  效果展示(尚未完善)

ChatUDPClientTest
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Common;
using UIWidgetsSamples;
using System;

/// <summary>
/// 服務端
/// </summary>
public class ChatUDPServerTest : MonoBehaviour
{
    public string serverIP;
    //IP地址
    public int serverPort;
    ////1.創建Scoket對象 IP Port
    private Thread thread;
    private UdpClient udpSeivic;
    public void Start()
    {
        chatView = transform.FindChildByName("ChatView").
            GetComponent<ChatView>();
        //給埠和IP
        //構建終結點  IP和一個埠
        IPEndPoint localEP = new 
            IPEndPoint(IPAddress.Parse(serverIP), serverPort);
        udpSeivic = new UdpClient(localEP);

        thread = new Thread(ReceiveMessage);
        thread.Start();
    }
    
    /// <summary>
    /// 接收消息
    /// </summary>
    private void ReceiveMessage()
    {
        while (true)
        {
            IPEndPoint remote = new
                IPEndPoint(IPAddress.Any, 0);
            //創建任意終結點
            //ref
            byte[] date = udpSeivic.Receive(ref remote);
            //Receive接收消息  如果沒有收到消息 線程阻塞  放線上程中
            string msg = Encoding.UTF8.GetString(date);
            //獲取的客戶都安信息
            Debug.Log(remote.Address + "===" + remote.Port);
            //如果接收客戶端的消息,會把任意終結點修改為客戶端的終結點
            ThreadCrossHelper.Instance.ExecuteOnMainThread(() => { ShowMessage(msg); });
        }
    }
    private ChatView chatView;
    /// <summary>
    /// 顯示消息
    /// </summary>
    /// <param name="msg"></param>
    public void ShowMessage(string msg)
    {
        chatView.DataSource.Add(new ChatLine()
        {
            UserName = "AnnnS",
            Message = msg,
            Time = DateTime.Now,
            Type = ChatLineType.User,
        });
    }
    private void OnApplicationQuit()
    {
        udpSeivic.Close();
        thread.Abort();
    }
}
ChatUDPServerTest

腳本引用的工具箱

  1. MonoSingleton (泛型單例)
  2. ThreadCrossHelper (為子線程提供,可以在主線程中執行的方法)
  3. TransformHelper(根據名稱查找後代元素)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Common
{
    /// <summary>
    /// 
    /// </summary>
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        //public static T Instance
        //{
        //    get;
        //    private set;
        //}
        //private void Awake()
        //{
        //    Instance = this as T;
        //} 
        //按需載入
        private static T instance;
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    //在場景中查找對象
                    instance = FindObjectOfType<T>();
                    if (instance == null)
                    {
                        //創建游戲對象 附加 腳本對象
                        new GameObject("Singleton of " + typeof(T)).AddComponent<T>();//立即執行Awake
                    }
                    else
                    {
                        instance.Initialized();
                    }
                }
                return instance;
            }
        }

        protected virtual void Initialized()
        {

        }

        [Tooltip("是否需要跨場景不銷毀")]
        public bool isDontDestroy = true;

        //如果管理類自行附加到物體中
        //在Awake中為instance賦值 
        protected void Awake()
        {
            if (isDontDestroy)
            {
                DontDestroyOnLoad(gameObject);
            }
            if (instance == null)
            {
                instance = this as T;
                instance.Initialized();
            }
        }
    }
}
MonoSingleton
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
namespace Common
{
    /// <summary>
    /// 
    /// </summary>
    public class ThreadCrossHelper : MonoSingleton<ThreadCrossHelper>
    {
        /// <summary>
        /// 延遲項
        /// </summary> 
        class DelayedItem
        {
            public Action CurrentAction { get; set; }
            public DateTime Time { get; set; }
        }

        private List<DelayedItem> actionList;
        //private List<Action> actionList;
        //private List<float> timeList;

        protected override void Initialized()
        {
            base.Initialized();

            actionList = new List<DelayedItem>(); 
        }

        private void Update()
        { 
            for (int i = actionList.Count - 1; i >= 0; i--)
            {
                //到時間
                if (actionList[i].Time <= DateTime.Now)
                {
                    lock (actionList)
                    {
                        actionList[i].CurrentAction();//執行
                        actionList.RemoveAt(i);//從列表中移除 
                    }
                }
            }
        }
        /// <summary>
        /// 為子線程提供,可以在主線程中執行的方法
        /// </summary>
        /// <param name="action"></param>
        /// <param name="dealy"></param>
        public void ExecuteOnMainThread(Action action, float dealy = 0)
        {
            DelayedItem item = new DelayedItem()
            {
                CurrentAction = action,
                //Time = Time.time + dealy
                Time = DateTime.Now.AddSeconds(dealy)
            };
            lock (actionList)
            {
                actionList.Add(item);
            }
        }
    }
}
ThreadCrossHelper
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Common
{
    /// <summary>
    /// 變換組件助手類
    /// </summary>
    public static  class TransformHelper
    { 
        /// <summary>
        /// 未知層級,根據名稱查找後代元素
        /// </summary>
        /// <param name="currentTF"></param>
        /// <param name="childName"></param>
        /// <returns></returns>
        public static Transform FindChildByName(this Transform currentTF, string childName)
        {
            Transform childTF = currentTF.Find(childName);
            if (childTF != null) return childTF;
            //將問題推遲給子物體
            for (int i = 0; i < currentTF.childCount; i++)
            {
                //在方法體內部,又遇到了相同的問題,所以需要調用自身。
                childTF = FindChildByName(currentTF.GetChild(i), childName);
                if (childTF != null) return childTF;
            }
            return null;
        }
    }
}
TransformHelper
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 添加default.cshtml 使用方法: 效果如圖: ...
  • 根據《互聯網信息服務管理辦法》以及《非經營性互聯網信息服務備案管理辦法》,所有對中國大陸提供服務的網站都必須先進行ICP備案,才可開通服務。如果網站的功能變數名稱未備案,並且網站存在中國大陸的伺服器上,則會被禁止訪問,因此首先要先進行功能變數名稱的備案操作,每個雲伺服器廠商都有相應的備案系統可以幫助用戶快捷的備案, ...
  • 在應用程式的開發中,文件操作的使用基本上是必不可少的,FileStream類、StreamWriter類、Directory類、DirectoryInfo類等都是文件操作中時常涉及到的類,我們可以通過封裝這一系列的文件操作為一個工具類,該工具類包含文件的讀寫、文件的追加、文件的拷貝、刪除文件、獲取指 ...
  • 在阿裡雲ECS伺服器的使用過程中,如果是安全意識高的運維人員,可能會發現雲伺服器廠商基本上提供的了個叫做安全組的功能設置項。安全組相當於一個虛擬的防火牆,類似於Windows系統的防火牆,在安全組內可以放行系統相應的埠號以及IP訪問的許可權(如設置只能某些IP才可訪問此台伺服器)等,安全組功能是雲服 ...
  • 在應用程式的開發中,如果資料庫中的數據量過於的龐大,則需要針對查詢數據做分頁處理,取出對應分頁中的數據,在Sqlserver分頁的語句寫法中,有兩種比較常用,一種是數據表中含有自增量Id的情況,可以根據Id的大小順序進行分頁,另一種是資料庫中不存在Int類型的Id的情況,此時就需要通過Row_Num ...
  • //實現層 分割線 public List<UserModel> ShowListPage(int pageindex, int pagesize) { string sql = string.Format("select top({0}) *from (select ROW_NUMBER() ov ...
  • 管理各種管理器 ///為什麼需要單例 ///單例模式核心在於對於某個單例類,在系統中同時只存在唯一一個實例,並且該實例容易被外界所訪問; ///避免創建過多的對象,意味著在記憶體中,只存在一個實例,減少了記憶體開銷; using System.Collections; using System.Coll ...
  • 在打開from設計界面時,報錯。 解決方法:將項目中Properties文件中licenses.licx刪除,重新建立一個空的licenses.licx文件放到項目中。 重新打開界面,解決 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...