亲宝软件园·资讯

展开

Unity聊天室功能 Unity实现聊天室功能

双鱼-布衣 人气:0
想了解Unity实现聊天室功能的相关内容吗,双鱼-布衣在本文为您仔细讲解Unity聊天室功能的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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();
 }
}

实际运行效果(注意需要先启动服务器):

加载全部内容

相关教程
猜你喜欢
用户评论