Unity实现聊天室功能
本文的例子共享了Unity实现聊天室功能的详细代码,供大家参考。详细内容如下
简单的聊天室功能,客户端发送消息后,服务器接收消息并分发给其他客户端,显示聊天内容
聊天室服务器
服务器需要有以下步骤
1、确定套接字协议类型(使用TCP协议或UDP协议)
2、绑定服务器的IP地址和端口号
3、设置最大监听号码
4、等待连接并处理消息
因为服务器属于一对多处理关系,所以我们需要使用线程来监听消息:
class Client { private Socket clientSocket; private Thread t; public bool Connected { get { return clientSocket.Connected; } } private byte[] data = new byte[1024];//数据容器 public Client(Socket client) { clientSocket = client; //启动一个线程,处理客户端的接受 t = new Thread(ReceiveMsg); t.Start(); } private void ReceiveMsg() { while (true) { //在接收数据之前,判断Socket连接是否断开 if (!clientSocket.Connected) { clientSocket.Close(); break;//跳出循环终止线程的执行 } int length=clientSocket.Receive(data); string msg = Encoding.UTF8.GetString(data, 0, length); //版本接收数据后,要将数据分发到客户端 //广播消息 Program.BroadcastMsg(msg); } } public void SendMsg(string msg) { byte[] data = Encoding.UTF8.GetBytes(msg); clientSocket.Send(data); } }
服务器主要代码:
class Program { static List<Client> clients = new List<Client>(); //本机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客户端代码很简单,只需监听服务器消息,在界面上显示就行了
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中不允许线上程中调用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)); //创建一个线程用来接收消息 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(); } }
实际运行效果(注重需要先启动服务器):