Unity實(shí)現(xiàn)簡(jiǎn)單的多人聊天工具
本文實(shí)例為大家分享了Unity實(shí)現(xiàn)多人聊天工具的具體代碼,供大家參考,具體內(nèi)容如下
代碼1 : 服務(wù)端代碼
using UnityEngine; using System.Net.Sockets; using System.Net; using System.Threading; public class ChatServer : MonoBehaviour { ? ? ? ?// 設(shè)置連接端口 ? ? ? ?const int portNo = 500; ? ? ? ?string m_ServerIP = ""; ? ? ? ?// Use this for initialization ? ? ? ?void Start () ? ? ? ?{ ? ? ? ? ? ? ? m_ServerIP = Network.player.ipAddress;//獲取本機(jī)服務(wù)器的IP ? ? ? ? ? ?print("服務(wù)器IP:"+m_ServerIP); ? ? ? ?//開啟新的線程來(lái)執(zhí)行TCP的監(jiān)聽 ? ? ? ? ? ? ? myThread.Start (); ? ? ? ? //支持后臺(tái)運(yùn)行避免最小化后不運(yùn)行 ? ? ? ? ? ? ? Application.runInBackground = true; ? ? ? ?} ? ? ? ?private void ListenClientConnect () ? ? ? ?{ ? ? ? ? ? ? ? Debug.Log("正在啟動(dòng)服務(wù)器!"); ? ? ? ? // 初始化服務(wù)器IP ? ? ? ? ? ?IPAddress localAdd = IPAddress.Parse(m_ServerIP); ? ? ? ? ? ? ? // 創(chuàng)建TCP偵聽器 ? ? ? ? ? ? ? TcpListener listener = new TcpListener (localAdd, portNo); ? ? ? ? ? ? ? listener.Start (); ? ? ? ? ? ?Debug.Log("服務(wù)器正在運(yùn)行中......."); ? ? ? ? ? ?//溫馨提示:建議使用Windows電腦運(yùn)行服務(wù)器,如果是Mac系統(tǒng)一定要看到打印這句話服務(wù)器才啟動(dòng)起來(lái)了,否則服務(wù)器表示沒有啟動(dòng) ? ? ? ? // 循環(huán)接受客戶端的連接請(qǐng)求 ? ? ? ? while (true) { ? ? ? ? ? ? //編寫各個(gè)客戶端的類,只要監(jiān)聽到有IP連接服務(wù)器,就實(shí)例化對(duì)應(yīng)的客戶端 ? ? ? ? ? ? ? ? ? ? ?ChatClient user = new ChatClient (listener.AcceptTcpClient()); ? ? ? ? ? ? ? ? ? ? ?// 顯示連接客戶端的IP與端口【只要有新的客戶端連接進(jìn)來(lái)就會(huì)打印打控制臺(tái)誰(shuí)進(jìn)來(lái)了】 ? ? ? ? ? ? ? ? ? ? ?print (user._clientIP + " 加入服務(wù)器\n"); ? ? ? ? ? ? ? } ? ? ? ?} }
代碼2 : 客戶端與服務(wù)端交互
using UnityEngine; using System.Collections; using System.Net.Sockets; using System; using System.Text; //各個(gè)客戶端自身應(yīng)該有的邏輯【進(jìn)入服務(wù)器離開服務(wù)器等】 public class ChatClient : MonoBehaviour { ? ? ? ? static Hashtable ALLClients = new Hashtable ();// 客戶端列表 ? ? private TcpClient _client;// 客戶端實(shí)體 ? ? ?public string _clientIP;// 客戶端IP ? ? private string _clientNick;// 客戶端昵稱 ? ? private byte[] data;// 消息數(shù)據(jù) ? ? private bool ReceiveNick = true;//是否從客戶端接受到他的昵稱[消息分割標(biāo)識(shí)] ? ? ? ?void Awake () ? ? ? ?{ ? ? ? ? ? ? ? Application.runInBackground = true; ? ? ? ?} ? ? //由服務(wù)器創(chuàng)建實(shí)例 ? ? ? ?public ChatClient (TcpClient client) ? ? ? ?{ ? ? ? ? //客戶端實(shí)體對(duì)象 ? ? ? ? ? ? ? this._client = client; ? ? ? ? ? ? ? this._clientIP = client.Client.RemoteEndPoint.ToString (); ? ? ? ? ? ? ? // 把當(dāng)前客戶端實(shí)例添加到客戶列表當(dāng)中 ? ? ? ? ? ? ? //第一個(gè)參數(shù)時(shí)IP,第二個(gè)為對(duì)應(yīng)客戶端 ? ? ? ? ? ? ? ALLClients.Add (this._clientIP, this); ? ? ? ? ? ? ? data = new byte[this._client.ReceiveBufferSize]; ? ? ? ? ? ? ? // 從服務(wù)端獲取消息 ? ? ? ? ? ? ? client.GetStream ().BeginRead (data, 0, System.Convert.ToInt32 (this._client.ReceiveBufferSize), ReceiveMessage, null); ? ? ? ?} ? ? ? ?// 從客戶端獲取消息 ? ? ? ? void ReceiveMessage (IAsyncResult ar) ? ? ? ?{ ? ? ? ? ? ? ? int bytesRead; ? ? ? ? ? ? ? try { ? ? ? ? ? ? ? ? ? ? ?lock (this._client.GetStream()) { ? ? ? ? ? ? ? ? ? ? ? ? ? ?bytesRead = this._client.GetStream ().EndRead (ar); ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? //沒有讀到數(shù)據(jù)說(shuō)明這個(gè)客戶端已經(jīng)掉線 ? ? ? ? ? ? ? ? ? ? ?if (bytesRead < 1) { ? ? ? ? ? ? ? ? ? ? ? ? ? ?ALLClients.Remove (this._clientIP); ? ? ? ? ? ? ? ? ? ? ? ? ? ?//廣播 ? ? ? ? ? ? ? ? ? ? ? ? ? ?Broadcast (this._clientNick + " 已經(jīng)離開服務(wù)器");//已經(jīng)離開服務(wù)器 ? ? ? ? ? ? ? ? ? ? ? ? ? ?return; ? ? ? ? ? ? ? ? ? ? ?} else { ? ? ? ? ? ? ? ? ? ? ? ? ? ?string messageReceived = Encoding.UTF8.GetString (data, 0, bytesRead); ? ? ? ? ? ? ? ? //這個(gè)開關(guān)很關(guān)鍵,讀取到了發(fā)送進(jìn)來(lái)的數(shù)據(jù)后,默認(rèn)是收到了對(duì)應(yīng)客戶端的昵稱的,將這個(gè)客戶端第一次發(fā)來(lái)的信息作為昵稱,以后的都是他發(fā)消息 ? ? ? ? ? ? ? ? ? ? ? ? ? ?if (ReceiveNick) { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? this._clientNick = messageReceived; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Broadcast (this._clientNick + " 已經(jīng)進(jìn)入服務(wù)器");//已經(jīng)進(jìn)入服務(wù)器 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ReceiveNick = false; ? ? ? ? ? ? ? ? ? ? ? ? ? ?} else { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Broadcast (this._clientNick + ":" + messageReceived); ? ? ? ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ? ? ? ?lock (this._client.GetStream()) { ? ? ? ? ? ? ? ? //尾遞歸處理 ? ? ? ? ? ? ? ? ? ? ? ? ? ?this._client.GetStream ().BeginRead (data, 0, System.Convert.ToInt32 (this._client.ReceiveBufferSize), ReceiveMessage, null); ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? } catch (Exception ex) { ? ? ? ? ? ? ? ? ? ? ?ALLClients.Remove (this._clientIP); ? ? ? ? ? ? ? ? ? ? ?Broadcast (this._clientNick + " 已經(jīng)離開服務(wù)器");//已經(jīng)離開服務(wù)器 ? ? ? ? ? ? ? } ? ? ? ?} ? ? ? ?// 向一個(gè)客戶端發(fā)送消息 ? ? ? ? void sendMessage (string message) ? ? ? ?{ ? ? ? ? ? ? ? try { ? ? ? ? ? ? ? ? ? ? ?NetworkStream ns; ? ? ? ? ? ? ? ? ? ? ?lock (this._client.GetStream()) { ? ? ? ? ? ? ? ? ? ? ? ? ? ?ns = this._client.GetStream (); ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ? ? ? ?// 對(duì)信息進(jìn)行編碼,寫入流,別忘記沖刷趕緊緩沖 ? ? ? ? ? ? ? ? ? ? ?byte[] bytesToSend = Encoding.UTF8.GetBytes (message); ? ? ? ? ? ? ? ? ? ? ?ns.Write (bytesToSend, 0, bytesToSend.Length); ? ? ? ? ? ? ? ? ? ? ?ns.Flush (); ? ? ? ? ? ? ? } catch (Exception ex) { ? ? ? ? ? ? ? ? ? ? ?Debug.Log ("Error:" + ex); ? ? ? ? ? ? ? } ? ? ? ?} ? ? ? ?// 向所有客戶端廣播消息 ? ? ? ? void Broadcast (string message) ? ? ? ?{ ? ? ? ? ? ? ? Debug.Log (message);//打印消息 ? ? ? ? //向在服務(wù)器中連接的所有客戶端發(fā)送最新消息 ? ? ? ? ? ? ? foreach (DictionaryEntry c in ALLClients) { ? ? ? ? ? ? ? ? ? ? ?((ChatClient)(c.Value)).sendMessage (message + Environment.NewLine); ? ? ? ? ? ? // ? \r是回車,英文是Carriage return ?運(yùn)輸返回 ? ? ? ? ? ?B位置 ? ? ? ? ? ? // ? \n是換行,英文是New line ? ? ? ? ? ? ? ? ? ? ? ? ? ?C位置 ? ? ? ? ? ? // ? Enter = 回車+換行(\r\n) 確認(rèn)按鍵 ? ? ? ? ? ? ? ? ? ?D位置 ? ? ? ? ? ? //在 Windows 環(huán)境中,C# 語(yǔ)言 Environment.NewLine == "\r\n" ? ? ? ? ? ? // B ? ? ? A ? ? ? ? ? ? // D ? ? ? C ? ? ? ? ? ? // 當(dāng)前編輯光標(biāo)位置:A ? ? ? ? ? ? //機(jī)械打字機(jī)有回車和換行兩個(gè)鍵作用分別是: ? ? ? ? ? ? //換行就是把滾筒卷一格,不改變水平位置。 ? ? ? ? ? ? //回車就是把水平位置復(fù)位,不卷動(dòng)滾筒。 ? ? ? ? } ? ? } }
代碼3 : 客戶端與UI交互
using UnityEngine; using System.Net.Sockets; using System; using System.Text; using UnityEngine.UI; //各個(gè)客戶端聊天的UI交互 public class ClientHandler : MonoBehaviour { ? ? ? ?const int portNo = 500; ? ? ? ?private TcpClient _client; ? ? ? ?private ?byte[] data; ? ? ? ? string nickName = ""; ? ? ? ? string message = ""; ? ? ? ? string sendMsg = ""; ? ? ? ?[SerializeField]InputField m_NickInput; ? ? ? ?[SerializeField]InputField m_SendMsgInput; ? ? ? ?[SerializeField]Text m_ShowMessageText; ? ? [SerializeField] InputField m_IPInput; ? ? ? ?void Update () ? ? ? ?{ ? ? ? ? ? ? ? nickName = m_NickInput.text; ? ? ? ? ? ? ? m_ShowMessageText.text = message; ? ? ? ? ? ? ? sendMsg = m_SendMsgInput.text; ? ? ? ?} ? ? //連接服務(wù)器按鈕 ? ? ? ?public void ConBtnOnClik () ? ? ? ?{ ? ? ? ? ? ?if (m_IPInput.text != "" || m_IPInput.text != null) ? ? ? ? ? ?{ ? ? ? ? ? ? //真正的當(dāng)前客戶端 ? ? ? ? ? ? ? ?this._client = new TcpClient(); ? ? ? ? ? ? ? ?//連接服務(wù)器的IP和端口 ? ? ? ? ? ? ? ?this._client.Connect(m_IPInput.text, portNo); ? ? ? ? ? ? ? ?//獲取緩沖區(qū)的位元組數(shù)目,即緩存區(qū)的大小 ? ? ? ? ? ? ? ?data = new byte[this._client.ReceiveBufferSize];//避免去去死,比如有些同志寫成1024 ? ? ? ? ? ? ? ?//點(diǎn)擊了連接服務(wù)器按鈕后就將昵稱也發(fā)送過(guò)去 ? ? ? ? ? ? ? ?SendMyMessage(nickName); ? ? ? ? ? ? //當(dāng)前客戶端開始去讀取數(shù)據(jù)流 ? ? ? ? ? ? ? ?this._client.GetStream() ? ? ? ? ? ? ? ? ? ?.BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null); ? ? ? ? ? ?} ? ? ? ? ? ?else ? ? ? ? ? ?{ ? ? ? ? ? ? ? ?Debug.Log("請(qǐng)輸入正確的IP"); ? ? ? ? ? ?} ? ? ? ?} ? ? //發(fā)送消息按鈕 ? ? ? ?public void SendBtnOnClik () ? ? ? ?{ ? ? ? ? //每次將輸入消息發(fā)送到服務(wù)器,并制空輸入框 ? ? ? ? ? ? ? SendMyMessage (sendMsg); ? ? ? ? ? ? ? m_SendMsgInput.text = ""; ? ? ? ?} ? ? ? ?/// <summary> ? ? ? ?/// 向服務(wù)器發(fā)送數(shù)據(jù)(發(fā)送聊天信息) ? ? ? ?/// </summary> ? ? ? ?/// <param name="message"></param> ? ? ? ? void SendMyMessage (string message) ? ? ? ?{ ? ? ? ? ? ? ? try { ? ? ? ? ? ? ? ? ? ? ?NetworkStream ns = this._client.GetStream (); ? ? ? ? ? ? //因?yàn)槲覀儸F(xiàn)在只做文本信息的傳輸,所以這里使用UTF編碼來(lái)寫入和識(shí)別 ? ? ? ? ? ? ? ? ? ? ?byte[] data = Encoding.UTF8.GetBytes (message); ? ? ? ? ? ? ? ? ? ? ?ns.Write (data, 0, data.Length); ? ? ? ? ? ? ? ? ? ? ?ns.Flush ();//沖刷趕緊buffer緩沖,準(zhǔn)備下次再接受新的數(shù)據(jù) ? ? ? ? ? ? ? } catch (Exception ex) { ? ? ? ? ? ? ? ? ? ? ?Debug.Log ("Error:" + ex); ? ? ? ? ? ? ? } ? ? ? ?} ? ? ? ?/// <summary> ? ? ? ?/// 接收服務(wù)器的數(shù)據(jù)(聊天信息) ? ? ? ?/// </summary> ? ? ? ?/// <param name="ar"></param> ? ? ? ? void ReceiveMessage (IAsyncResult ar) ? ? ? ?{ ? ? ? ? ? ? ? try { ? ? ? ? ? ? //當(dāng)上面的讀取方法執(zhí)行完畢后,會(huì)自動(dòng)回調(diào)這個(gè)方法 ? ? ? ? ? ? ? ? ? ? ?int bytesRead = this._client.GetStream ().EndRead (ar);//讀取完畢 ? ? ? ? ? ? ? ? ? ? ?if (bytesRead < 1) { ? ? ? ? ? ? ? ? //說(shuō)明沒有讀取到任何信息 ? ? ? ? ? ? ? ? ? ? ? ? ? ?return; ? ? ? ? ? ? ? ? ? ? ?} else { ? ? ? ? ? ? ? ? //讀取到文本信息后使用UTF編碼解碼 ? ,并連續(xù)拼接起來(lái) ? ? ? ? ? ? ? ? ? ? ? ? ? ?message += Encoding.UTF8.GetString (data, 0, bytesRead); ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? //再次去讀取信息 ? ? ? ? ? ? _client.GetStream ().BeginRead (data, 0, Convert.ToInt32 (_client.ReceiveBufferSize), ReceiveMessage, null); ? ? ? ? ? ? ? } catch (Exception ex) { ? ? ? ? ? ? ? ? ? ? ?print ("Error:" + ex); ? ? ? ? ? ? ? } ? ? ? ?} }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C# 連接SQL數(shù)據(jù)庫(kù)的方法及常用連接字符串
這篇文章主要介紹了C# 連接SQL數(shù)據(jù)庫(kù)的方法及常用連接字符串,有需要的朋友可以參考一下2014-01-01講解C#面相對(duì)象編程中的類與對(duì)象的特性與概念
這篇文章主要介紹了C#面相對(duì)象編程中的類與對(duì)象的特性與概念,OOP面向?qū)ο笳Z(yǔ)言相對(duì)C語(yǔ)言這樣面相過(guò)程的語(yǔ)言來(lái)說(shuō)具有類和對(duì)象以及方法這樣的特性,需要的朋友可以參考下2016-01-01C#聯(lián)合VisionPro實(shí)現(xiàn)TCP/IP通信詳解
TCP/IP(傳輸控制協(xié)議/互聯(lián)網(wǎng)協(xié)議)是一組用于在網(wǎng)絡(luò)上進(jìn)行通信的通信協(xié)議,本文主要為大家詳細(xì)介紹了C#如何聯(lián)合VisionPro實(shí)現(xiàn)TCP/IP通信,希望對(duì)大家有所幫助2024-02-02C#中winform中panel重疊無(wú)法顯示問題的解決
這篇文章主要介紹了C#中winform中panel重疊無(wú)法顯示問題的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10C#將hashtable值轉(zhuǎn)換到數(shù)組中的方法
這篇文章主要介紹了C#將hashtable值轉(zhuǎn)換到數(shù)組中的方法,涉及C#中CopyTo方法的使用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04