unity 基于socket的多人群聊实现1

来源:互联网 发布:360 camera软件 编辑:程序博客网 时间:2024/05/29 04:33

unity 基于socket的多人群聊实现1

服务器

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 ConsoleApplication1{    class Program    {        static List<Socket> socketList = new List<Socket>();        //static Socket server;</span>        //static Dictionary<EndPoint, Socket> socketDic = new Dictionary<EndPoint, Socket>();</span>        static void Main(string[] args)        {            //实例化服务端socket对象</span>            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            IPAddress ip = new IPAddress(new byte[] { 192,168,10,12 });//169, 254, 202, 67            int port = 6000;            EndPoint point = new IPEndPoint(ip, port);//封装保存IP和端口号</span>            server.Bind(point);//把IP和端口号保存到服务端socket对象</span>            server.Listen(10);//监听服务端</span>            Console.WriteLine("服务器启动。。。");            server.BeginAccept(new AsyncCallback(AcceptClient), server);            //while (true)</span>            //{</span>            //    Socket client = server.Accept();//保存连接进来的服务端对象</span>            //    Console.WriteLine("有新客户端连接。。。");</span>            //    socketList.Add(client);</span>            //    Console.WriteLine("客户ip信息:" + client.RemoteEndPoint);</span>            //    string msg = "系统信息:欢迎来到德莱联盟";</span>            //    byte[] data = Encoding.UTF8.GetBytes(msg);</span>            //    client.Send(data);//给客户端发送信息</span>            //    Thread t = new Thread(ReceiveMsg);</span>            //    t.Start(client);</span>            //}</span>            Console.ReadKey();        }        static void AcceptClient(IAsyncResult ar)        {            Socket myserver = ar.AsyncState as Socket;            Socket client = myserver.EndAccept(ar);//保存异步连接的客户端</span>            Console.WriteLine("有新客户端连接。。。");            socketList.Add(client);            Console.WriteLine("客户ip信息:" + client.RemoteEndPoint);            string msg = "系统信息:欢迎来到德莱联盟";            byte[]    data = Encoding.UTF8.GetBytes(msg);            client.Send(data);//给客户端发送信息</span>            Thread t = new Thread(ReceiveMsg);            t.Start(client);            myserver.BeginAccept(new AsyncCallback(AcceptClient), myserver);        }        //接收信息</span>        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);//显示异常信息</span>                    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;</span>                IPEndPoint po = mySocket.RemoteEndPoint as IPEndPoint;                string ip = po.Address.ToString();                resMsg = ip + ":" + resMsg;                Console.WriteLine(resMsg);                sendAllMsg(resMsg);            }        }        //群发消息</span>        static void sendAllMsg(string resMsg)        {            //把接收到的消息群发出去</span>            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;using UnityEngine.UI;public class Socket_Client : MonoBehaviour{    public Text msgLable;    public InputField input;    public Button sendBtn;    Socket client;    string message = "";    //初始化     void Awake()    {    }    void Start()    {        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);        client.Connect(new IPEndPoint(IPAddress.Parse("192.168.10.16"), 6000));        //ReceiveMsg();         Thread t = new Thread(new ThreadStart(ReceiveMsg));        t.Start();    }    public void OnSendBtnClick()    {        client.Send(Encoding.UTF8.GetBytes(input.text));        input.text = "";    }    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();    }}
原创粉丝点击