使用unity UGUI 利用Socket 实现 多客户端通讯

unity  5.1.1  UGUI    VS2013


服务器端:

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

namespace SocketSever
{
    class Program
    {   static ListclientList =new List();  //建立连接的数组!!!!
        /// 
        /// 广播消息
        /// 
        /// 
        public  static void BroadcastMessage(string message)
    {   var notConnectedList = new List();
        foreach (var client in clientList)
        {
            if (client.Connected)
            {
                client.SendMessage(message);
            }
            else
            {
                notConnectedList.Add(client);
            }
        }
        foreach (var temp in notConnectedList)
        {
            clientList.Remove(temp);
        }
    }
        static void Main(string[] args)
        {
            int port = 6180;               //端口
            string host = "192.168.10.75"; //IP
            //创建终结点
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);

            //创建Socket并开始监听
            Socket TcpSever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
//创建一个Socket对象,如果用UDP协议,则要用SocketTyype.Dgram类型的套接字
            TcpSever.Bind(ipe);                                                                            //绑定EndPoint对象(6180端口和ip地址)
            TcpSever.Listen(100);            //开始监听 监听数//接受到Client连接,为此连接建立新的Socket,并接受消息
         Console.WriteLine("等待客户端连接。。。。。");
                                             //死循环接受新的连接
            while(true){
            Socket temp = TcpSever.Accept();  //为新建立的连接创建新的Socket
            Console.WriteLine("有一个已经连接过来了!");
            Client client = new Client(temp); //把与客户的通讯交互逻辑做到Client 类里面(收发消息)
            clientList.Add(client);           //新的连接放入集合
            }


            //Console.WriteLine("建立连接");
            //string recvStr = "";
            //byte[] recvBytes = new byte[1024];
            //int bytes;
            //bytes = temp.Receive(recvBytes, recvBytes.Length, 0); //从客户端接受消息
            //recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);

            ////给Client端返回信息
            //Console.WriteLine("server get message:{0}", recvStr);    //把客户端传来的信息显示出来
            //string sendStr = "ok!Client send message successful!";
            //byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            //temp.Send(bs, bs.Length, 0);                             //返回信息给客户端
            //temp.Close();
            //TcpSever.Close();
            //Console.ReadLine();
        }
    }
}
   

Client 类:

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

namespace SocketSever
{
    /// 
    /// 与客户端做通讯
    /// 
    class Client
    {
        private Socket clientSocket;
        private Thread t;//建立线程
        private byte[] data=new byte[1024];//数据容器
        public Client(Socket s)
        {
            clientSocket = s;
            //启动一个线程处理接收客户端的数据
            t = new Thread(ReceiveMessage);
            t.Start();
        }
        private void ReceiveMessage()
        {
            while(true){
                //在接收数据之前 判断Socket连接是否断开
                if (clientSocket.Poll(10,SelectMode.SelectRead))
                {
                    clientSocket.Close();
                    break;//跳出循环 终止线程
                }
                try
                {
                    int length = clientSocket.Receive(data);
                    string message = Encoding.UTF8.GetString(data, 0, length);
                    //TODO:接收数据之后把数据分发到客户端
                    //广播这个消息!!!!!!!!!
                    Program.BroadcastMessage(message);
                    Console.WriteLine("客户端发来的消息:" + message);
                }
                catch (Exception ex) { Console.WriteLine("有一个退出了:" +"这是一个异常"); }
            }
        }
        /// 
        /// 分发出去
        /// 
        /// 
        public void SendMessage(string message)
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            clientSocket.Send(data);
        }
        public bool Connected
        {
            get { return clientSocket.Connected; }
        }
    }
}

unity 源码         客户端在关闭的时候没有关闭Socket连接,存在异常!!!!!
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine.UI;
using System.Threading;

public class ChatManager : MonoBehaviour
{
    public string ipaddress = "192.168.10.75";
    public int port = 6180;    //端口
    private Socket clientSocket;  //Socket 对象
    public Text T;   //输出框
    string message = "";
    public InputField InputText;//发送框
    public InputField Username;//用户名
    private Thread t;
    private byte[] data = new byte[1024];
    void Start()
    {
        ConnectToServer(); //创建连接
    }

    void Update()
    {
        if (message != null && message != "")
        {
            T.text += message + "\n";
            message = "";//清空消息
        }
    }
    /// 
    /// 与服务器建立连接
    /// 
    void ConnectToServer()
    {
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //与服务器建立连接
        clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipaddress), port));
        //创建一个新的线程 用来接收数据
        t = new Thread(ReceiveMessage);//开启线程
        t.Start();
    }
    /// 
    /// 这个线程方法用来循环接受消息
    /// 
    void ReceiveMessage()
    {
        while (true)
        {
            if (!clientSocket.Connected)
            {
                break;
            }
            int length = clientSocket.Receive(data);
            message = Encoding.UTF8.GetString(data, 0, length);
        }
    }
    /// 
    /// 向服务器发送数据
    /// 
    /// 
    void SendMessage(string message)
    {
        byte[] data = Encoding.UTF8.GetBytes(message);
        clientSocket.Send(data);
    }
    /// 
    /// 点击发送数据
    /// 
    public void OnSendButtonClick()
    {
        SendMessage(Username.text+":"+InputText.text);
        InputText.text = "";
    }
}


 
  使用unity UGUI 利用Socket 实现 多客户端通讯_第1张图片 
  

你可能感兴趣的:(unity)