Unity實(shí)現(xiàn)聊天室功能
本文實(shí)例為大家分享了Unity實(shí)現(xiàn)聊天室功能的具體代碼,供大家參考,具體內(nèi)容如下
簡(jiǎn)單聊天室功能,客戶端發(fā)送消息后,服務(wù)器接收到消息后分發(fā)到其它客戶端上并顯示聊天內(nèi)容
聊天室服務(wù)器
服務(wù)器需要有以下幾個(gè)步驟
1、確定Socket協(xié)議類型(采用TCP協(xié)議或者UDP協(xié)議)
2、綁定服務(wù)器的IP地址和端口號(hào)
3、設(shè)置最大監(jiān)聽數(shù)量
4、等到連接并處理消息
由于服務(wù)器屬于一對(duì)多的處理關(guān)系,因?yàn)槲覀冃枰镁€程來(lái)監(jiān)聽消息:
class Client { private Socket clientSocket; private Thread t; public bool Connected { get { return clientSocket.Connected; } } private byte[] data = new byte[1024];//數(shù)據(jù)容器 public Client(Socket client) { clientSocket = client; //啟動(dòng)一個(gè)線程,處理客戶端的接受 t = new Thread(ReceiveMsg); t.Start(); } private void ReceiveMsg() { while (true) { //在接收數(shù)據(jù)之前,判斷Socket連接是否斷開 if (!clientSocket.Connected) { clientSocket.Close(); break;//跳出循環(huán)終止線程的執(zhí)行 } int length=clientSocket.Receive(data); string msg = Encoding.UTF8.GetString(data, 0, length); //服務(wù)端接收數(shù)據(jù)后,要將數(shù)據(jù)分發(fā)到客戶端 //廣播消息 Program.BroadcastMsg(msg); } } public void SendMsg(string msg) { byte[] data = Encoding.UTF8.GetBytes(msg); clientSocket.Send(data); } }
服務(wù)器主要代碼:
class Program { static List<Client> clients = new List<Client>(); //本機(jī)IP:192.168.100.172 static void Main(string[] args) { Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); tcpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.100.172"), 7788)); tcpServer.Listen(5000); Console.WriteLine("Server Running......."); while (true) { var clientSocket = tcpServer.Accept(); Console.WriteLine("建立連接"); Client client = new Client(clientSocket); clients.Add(client); } } public static void BroadcastMsg(string msg) { var noConnecteds = new List<Client>(); foreach (var client in clients) { if (client.Connected) { client.SendMsg(msg); } else { noConnecteds.Add(client); } } foreach (var del in noConnecteds) { clients.Remove(del); } } }
Unity客戶端代碼
Unity客戶端代碼就十分簡(jiǎn)單,監(jiān)聽服務(wù)器的消息并顯示到界面上即可
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Net; using System.Net.Sockets; using System.Text; using UnityEngine.UI; using System.Threading; public class ChatManager : MonoBehaviour { public string IP = "192.168.100.172"; public int Port = 7788; private Socket client; private Thread t; public InputField input; public Button sendBtn; public Text item; public string name; private string msg=string.Empty; // Start is called before the first frame update void Start() { ConnectedToServer(); sendBtn.onClick.AddListener(() => { SendMsg(input.text); input.text = string.Empty; }); } // Update is called once per frame void Update() { //由于在Unity中不允許在線程中調(diào)用UnityAPI,因此需要的Update中刷新顯示 if (!string.IsNullOrEmpty(msg)) { item.text += "\n" + msg; msg = string.Empty; } } private void ConnectedToServer() { client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(new IPEndPoint(IPAddress.Parse(IP), Port)); //創(chuàng)建一個(gè)線程用來(lái)接收消息 t = new Thread(ReceiveMsg); t.Start(); } byte[] data = new byte[1024]; public void ReceiveMsg() { while (true) { if (!client.Connected) { break; } int length = client.Receive(data); msg = Encoding.UTF8.GetString(data, 0, length); } } public void SendMsg(string msg) { byte[] data = Encoding.UTF8.GetBytes(name+":"+msg); client.Send(data); } public void OnDestroy() { client.Close(); } }
實(shí)際運(yùn)行效果(注意需要先啟動(dòng)服務(wù)器):
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C# 運(yùn)算符 ?、??、?: 各種問(wèn)號(hào)的用法和說(shuō)明
本文介紹C#中三種常見的問(wèn)號(hào)運(yùn)算符的使用方法,簡(jiǎn)單講解給大家,希望對(duì)大家有所幫助。2016-04-04DataGridView實(shí)現(xiàn)點(diǎn)擊列頭升序和降序排序
這篇文章介紹了DataGridView實(shí)現(xiàn)點(diǎn)擊列頭升序和降序排序的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02C#實(shí)現(xiàn)在PDF文檔中應(yīng)用多種不同字體
在PDF文檔中,可繪制不同字體樣式、不同語(yǔ)言的文字,可通過(guò)使用Standard字體、TrueType字體、CJK字體或者自定義(私有)等字體類型。本文將具體介紹實(shí)現(xiàn)的方法,需要的可以參考一下2022-01-01C#8.0默認(rèn)接口實(shí)現(xiàn)的詳細(xì)實(shí)例
Microsoft使用C#8.0發(fā)布了許多新功能,他們引入的主要功能之一是默認(rèn)接口方法。這篇文章主要給大家介紹了關(guān)于C#8.0默認(rèn)接口實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下2021-05-05C#實(shí)現(xiàn)根據(jù)年份計(jì)算生肖屬相的方法
這篇文章主要介紹了C#實(shí)現(xiàn)根據(jù)年份計(jì)算生肖屬相的方法,涉及C#數(shù)組與字符串的操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03