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();
    }
}

实际运行效果(注意需要先启动服务器):
在这里插入图片描述

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值