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


}
  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天涯过客TYGK

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值