unity 基于socket的多人群聊实现

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

<code class="hljs cs has-numbering"><span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.Collections.Generic;
<span class="hljs-keyword">using</span> System.Linq;
<span class="hljs-keyword">using</span> System.Text;
<span class="hljs-keyword">using</span> System.Threading.Tasks;
<span class="hljs-keyword">using</span> System.Net.Sockets;
<span class="hljs-keyword">using</span> System.Net;
<span class="hljs-keyword">using</span> System.Threading;

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

            server.Bind(point);<span class="hljs-comment">//把IP和端口号保存到服务端socket对象</span>
            server.Listen(<span class="hljs-number">10</span>);<span class="hljs-comment">//监听服务端</span>
            Console.WriteLine(<span class="hljs-string">"服务器启动。。。"</span>);
            server.BeginAccept(<span class="hljs-keyword">new</span> AsyncCallback(AcceptClient), server);

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

            <span class="hljs-comment">//}</span>
            Console.ReadKey();

        }

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

            myserver.BeginAccept(<span class="hljs-keyword">new</span> AsyncCallback(AcceptClient), myserver);

        }




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

                <span class="hljs-keyword">string</span> resMsg = Encoding.UTF8.GetString(buffer, <span class="hljs-number">0</span>, length);

                <span class="hljs-comment">//resMsg = mySocket.RemoteEndPoint.ToString() + ":" + resMsg;</span>
                IPEndPoint po = mySocket.RemoteEndPoint <span class="hljs-keyword">as</span> IPEndPoint;
                <span class="hljs-keyword">string</span> ip = po.Address.ToString();
                resMsg = ip + <span class="hljs-string">":"</span> + resMsg;
                Console.WriteLine(resMsg);
                sendAllMsg(resMsg);



            }

        }



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


}
</code>

客户端脚本:

<code class="hljs cs has-numbering"><span class="hljs-keyword">using</span> UnityEngine;
<span class="hljs-keyword">using</span> System.Collections;
<span class="hljs-keyword">using</span> System.Net;
<span class="hljs-keyword">using</span> System.Net.Sockets;
<span class="hljs-keyword">using</span> System.Text;
<span class="hljs-keyword">using</span> System.Threading;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> Socket_Client : MonoBehaviour
{
    <span class="hljs-keyword">public</span> UILabel msgLable;
    <span class="hljs-keyword">public</span> UIInput input;
    <span class="hljs-keyword">public</span> UIButton sendBtn;
    Socket client;
    <span class="hljs-keyword">string</span> message = <span class="hljs-string">""</span>;
    <span class="hljs-comment">//初始化</span>
    <span class="hljs-keyword">void</span> Awake()
    {

    }

    <span class="hljs-keyword">void</span> Start()
    {
        client = <span class="hljs-keyword">new</span> Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.Connect(<span class="hljs-keyword">new</span> IPEndPoint(IPAddress.Parse(<span class="hljs-string">"169.254.202.67"</span>), <span class="hljs-number">6000</span>));
        EventDelegate.Add(sendBtn.onClick, OnSendBtnClick);
        <span class="hljs-comment">//ReceiveMsg();</span>
        Thread t = <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> ThreadStart(ReceiveMsg));
        t.Start();

    }

    <span class="hljs-keyword">void</span> OnSendBtnClick()
    {
        client.Send(Encoding.UTF8.GetBytes(input.<span class="hljs-keyword">value</span>));
        input.<span class="hljs-keyword">value</span> = <span class="hljs-string">""</span>;
    }

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

    }

    <span class="hljs-comment">// 更新数据</span>
    <span class="hljs-keyword">void</span> Update()
    {
        msgLable.text = message;
    }

    <span class="hljs-keyword">void</span> OnDestroy()
    {
        client.Close();
    }


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