unity 基于socket的多人群聊实现

通过c#开发服务器端,unity搭建客户端。实现客户端多用户之间消息的收发,类似于群聊的一种效果。
先看一下程序最终运行效果图:
这里写图片描述
服务端程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace Socket_服务端
{
    class Program
    {
        static List<Socket> socketList = new List<Socket>();
        //static Socket server;
        //static Dictionary<EndPoint, Socket> socketDic = new Dictionary<EndPoint, Socket>();
        static void Main(string[] args)
        {
            //实例化服务端socket对象
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = new IPAddress(new byte[] { 169, 254, 202, 67 });
            int port = 6000;
            EndPoint point = new IPEndPoint(ip, port);//封装保存IP和端口号

            server.Bind(point);//把IP和端口号保存到服务端socket对象
            server.Listen(10);//监听服务端
            Console.WriteLine("服务器启动。。。");
            server.BeginAccept(new AsyncCallback(AcceptClient), server);

            //while (true)
            //{
            //    Socket client = server.Accept();//保存连接进来的服务端对象
            //    Console.WriteLine("有新客户端连接。。。");
            //    socketList.Add(client);
            //    Console.WriteLine("客户ip信息:" + client.RemoteEndPoint);
            //    string msg = "系统信息:欢迎来到德莱联盟";
            //    byte[] data = Encoding.UTF8.GetBytes(msg);
            //    client.Send(data);//给客户端发送信息
            //    Thread t = new Thread(ReceiveMsg);
            //    t.Start(client);

            //}
            Console.ReadKey();

        }

        static void AcceptClient(IAsyncResult ar)
        {
            Socket myserver=ar.AsyncState as Socket;
            Socket client = myserver.EndAccept(ar);//保存异步连接的客户端
            Console.WriteLine("有新客户端连接。。。");
            socketList.Add(client);
            Console.WriteLine("客户ip信息:" + client.RemoteEndPoint);
            string msg = "系统信息:欢迎来到德莱联盟";
            byte[] data = Encoding.UTF8.GetBytes(msg);
            client.Send(data);//给客户端发送信息
            Thread t = new Thread(ReceiveMsg);
            t.Start(client);

            myserver.BeginAccept(new AsyncCallback(AcceptClient), myserver);

        }




        //接收信息
        static void ReceiveMsg(Object socket)
        {
            Socket mySocket = socket as Socket;
            while (true)
            {
                byte[] buffer = new byte[1024];
                int length = 0;
                try
                {
                    length = mySocket.Receive(buffer);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception:" + e.Message);//显示异常信息
                    IPEndPoint point = mySocket.RemoteEndPoint as IPEndPoint;
                    string ipp = point.Address.ToString();
                    Console.WriteLine(ipp + "退出回话");
                    socketList.Remove(mySocket);
                    sendAllMsg(ipp + "有人退出回话");
                    break;
                }

                string resMsg = Encoding.UTF8.GetString(buffer, 0, length);

                //resMsg = mySocket.RemoteEndPoint.ToString() + ":" + resMsg;
                IPEndPoint po = mySocket.RemoteEndPoint as IPEndPoint;
                string ip = po.Address.ToString();
                resMsg = ip + ":" + resMsg;
                Console.WriteLine(resMsg);
                sendAllMsg(resMsg);



            }

        }



        //群发消息
        static void sendAllMsg(string resMsg)
        {
            //把接收到的消息群发出去
            for (int i = 0; i < socketList.Count; i++)
            {
                socketList[i].Send(Encoding.UTF8.GetBytes(resMsg));
            }
        }
    }


}

客户端脚本:

using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class Socket_Client : MonoBehaviour
{
    public UILabel msgLable;
    public UIInput input;
    public UIButton sendBtn;
    Socket client;
    string message = "";
    //初始化
    void Awake()
    {

    }

    void Start()
    {
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.Connect(new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6000));
        EventDelegate.Add(sendBtn.onClick, OnSendBtnClick);
        //ReceiveMsg();
        Thread t = new Thread(new ThreadStart(ReceiveMsg));
        t.Start();

    }

    void OnSendBtnClick()
    {
        client.Send(Encoding.UTF8.GetBytes(input.value));
        input.value = "";
    }

    void ReceiveMsg()
    {
        while (true)
        {
            byte[] buffer = new byte[1024];
            int length = client.Receive(buffer);
            string resMsg = "\n" + Encoding.UTF8.GetString(buffer, 0, length);
            string st = msgLable.text;
            Debug.Log("res="+ resMsg);
            message = st+resMsg;
        }

    }

    // 更新数据
    void Update()
    {
        msgLable.text = message;
    }

    void OnDestroy()
    {
        client.Close();
    }


}
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页