Unity實現聊天室功能

本文實例為大傢分享瞭Unity實現聊天室功能的具體代碼,供大傢參考,具體內容如下

簡單聊天室功能,客戶端發送消息後,服務器接收到消息後分發到其它客戶端上並顯示聊天內容

聊天室服務器

服務器需要有以下幾個步驟

1、確定Socket協議類型(采用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();
 }
}

實際運行效果(註意需要先啟動服務器):

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: