Unity3D:TCPSocket模块

服务端Socket-
上接口

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

namespace YDB.TCPSocket
{
    public interface IServerSocket
    {
        /// 
        /// 连接并接收数据
        /// 
        void StartAccept(string receiveIP_str, string receivePort_str, Action<byte[]> action);
        /// 
        /// 发送数据
        /// 
        /// 
        /// 
        /// 
        void SendPackage(byte[] data);
        /// 
        /// 关闭
        /// 
        void ShutDown();
    }
}

在实现前,因为服务器需要接收客户端,所以定义一个类来保存客户端



using System;
using System.Net;
using System.Net.Sockets;

namespace YDB.TCPSocket
{
    public class SocketInfo
    {
        public Socket ClientSocket { get; private set; }
        public string ServerIP { get; private set; }
        public int ServerPort { get; private set; }
        public string ClientIP { get; private set; }
        public int ClientPort { get; private set; }
        public SocketAsyncEventArgs SocketAsyncEventArgs { get; private set; }
        public Action<byte[]> Callback { get; private set; }
        public static SocketInfo Create(Socket socket,Action<byte[]> callBack,SocketAsyncEventArgs socketAsyncEventArgs)
        {
            SocketInfo socketInfo = new SocketInfo();
            socketInfo.Callback = callBack;
            socketInfo.ClientSocket = socket;
            IPEndPoint iPEndPoint = socket.LocalEndPoint as IPEndPoint;
            socketInfo.ServerIP = iPEndPoint == null ? "" : iPEndPoint.Address.ToString();
            socketInfo.ServerPort = iPEndPoint == null ? -1 : iPEndPoint.Port;
            IPEndPoint remoteEndPoint = socket.RemoteEndPoint as IPEndPoint;
            socketInfo.ClientIP = remoteEndPoint == null ? "" : remoteEndPoint.Address.ToString();
            socketInfo.ClientPort = remoteEndPoint == null ? -1 : remoteEndPoint.Port;
            socketInfo.SocketAsyncEventArgs = socketAsyncEventArgs;
            return socketInfo;
        }
    }
}

接口具体实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace YDB.TCPSocket
{
    public class TCPServer_Socket : IServerSocket
    {
        //接收数据容量大小
        private const int BufferSize = 1024;
        //Socket
        protected Socket mSocket;
        //连接进来的客户端列表
        private Dictionary<string,SocketInfo> mClientSockets = new Dictionary<string, SocketInfo>();

        public TCPServer_Socket()
        {
            mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
        /// 
        /// 关闭
        /// 
        public void ShutDown()
        {
            if (mSocket == null)
            {
                return;
            }
            try
            {
                mSocket.Shutdown(SocketShutdown.Both);
                mSocket.Close();
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }
        #region 接收数据
        /// 
        /// 测试时,不能以127.0.0.1测试
        /// 
        /// IP
        /// Port
        /// 数据转换,默认Json
        public void StartAccept(string receiveIP_str, string receivePort_str,Action<byte[]> action)
        {
            if (string.IsNullOrEmpty(receiveIP_str) || string.IsNullOrEmpty(receivePort_str))
            {
                return;
            }
            int receivePort = int.Parse(receivePort_str);
            OnStartAccept(receiveIP_str, receivePort,action);
        }
        /// 
        /// 接收数据
        /// 
        /// 
        private void OnStartAccept(string receiveIP_str, int receivePort_str, Action<byte[]> action)
        {
            try
            {
                IPEndPoint receiveIPEndPoint = new IPEndPoint(IPAddress.Parse(receiveIP_str), receivePort_str);
                Debug.Log(string.Format("绑定IP:{0}和Port:{1}", receiveIP_str, receivePort_str));
                mSocket.Bind(receiveIPEndPoint);
                mSocket.Listen(10);

                SocketAsyncEventArgs receiveCompletedEventArgs = new SocketAsyncEventArgs();
                receiveCompletedEventArgs.Completed += AcceptCompolited;
                receiveCompletedEventArgs.UserToken = action;

                OnAccept(receiveCompletedEventArgs);
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }

        private void OnAccept(SocketAsyncEventArgs socketAsyncEventArgs)
        {
            Debug.Log("等待接收客户端");
            try
            {
                bool result = mSocket.AcceptAsync(socketAsyncEventArgs);
                if (result == false)
                {
                    ProcessAccept(socketAsyncEventArgs);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }
        /// 
        /// 接收数据完成回调事件
        /// 
        /// 
        /// 
        private void AcceptCompolited(object sender, SocketAsyncEventArgs e)
        {
            ProcessAccept(e);
        }
        /// 
        /// 处理接收事件
        /// 
        /// 
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            try
            {
                //接收到的Socket还是服务器的Socket,RemoteIP/Port被赋值
                Socket socket = e.AcceptSocket;
                Action<byte[]> callback = e.UserToken as Action<byte[]>;

                IPEndPoint point = socket.RemoteEndPoint as IPEndPoint;
                Console.WriteLine("接收到了" + point.Address.ToString() + ":" + point.Port.ToString());

                SocketAsyncEventArgs receiveAsyncEventArgs = new SocketAsyncEventArgs();
                receiveAsyncEventArgs.SetBuffer(new byte[BufferSize], 0, BufferSize);
                receiveAsyncEventArgs.Completed += ReceiveCompleted;
                SocketInfo receiveSocketInfo = SocketInfo.Create(socket, callback, receiveAsyncEventArgs);
                receiveAsyncEventArgs.UserToken = receiveSocketInfo;

                OnReceive(receiveSocketInfo);
                mClientSockets.Add(receiveSocketInfo.ClientIP+receiveSocketInfo.ClientPort, receiveSocketInfo);
                Debug.Log(receiveSocketInfo.ClientIP + ":" + receiveSocketInfo.ClientPort + "已连接");

                e.AcceptSocket = null;

                OnAccept(e);
            }
            catch (Exception exception)
            {

                throw new Exception(exception.ToString());
            }
        }

        /// 
        /// 递归接收入口
        /// 
        /// 
        private void OnReceive(SocketInfo socketInfo)
        {
            Socket socket = socketInfo.ClientSocket;
            bool result = socket.ReceiveAsync(socketInfo.SocketAsyncEventArgs);
            if (result == false)
            {
                ProcessReceive(socketInfo.SocketAsyncEventArgs);
            }
        }
        /// 
        /// 接收完成
        /// 
        /// 
        /// 
        private void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
        {
            ProcessReceive(e);
        }
        /// 
        /// 接收完成后处理事件
        /// 
        /// 
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
            {
                byte[] data = new byte[BufferSize];
                Buffer.BlockCopy(e.Buffer, 0, data, 0, e.BytesTransferred);

                e.SetBuffer(new byte[BufferSize], 0, BufferSize);
                
                SocketInfo socketInfo = e.UserToken as SocketInfo;
                Action<byte[]> callback = socketInfo.Callback;
                callback(data);

                OnReceive(socketInfo);
            }
            else
            {
                if (e.BytesTransferred == 0)
                {
                    if (e.SocketError == SocketError.Success)
                    {
                        //客户端主动断开连接
                        Debug.LogError("客户端主动断开连接");
                    }
                    else
                    {
                        Debug.LogError("网络异常");
                    }
                }
            }
        }

        #endregion
        #region 发送数据

        /// 
        /// 发送数据
        /// 
        /// 
        public void SendPackage(byte[] data)
        {
            try
            {
                foreach (var item in mClientSockets.Values)
                {
                    EndPoint sendEndPoint = new IPEndPoint(IPAddress.Parse(item.ClientIP), item.ClientPort);
                    SocketAsyncEventArgs mSendAsyncEventArgs = new SocketAsyncEventArgs();
                    mSendAsyncEventArgs.UserToken = item;
                    mSendAsyncEventArgs.RemoteEndPoint = sendEndPoint;
                    mSendAsyncEventArgs.Completed += SendCompolited;
                    mSendAsyncEventArgs.SetBuffer(data, 0, data.Length);
                    bool result = item.ClientSocket.SendToAsync(mSendAsyncEventArgs);
                    if (result == false)
                    {
                        ProcessSend(mSendAsyncEventArgs);
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }

        private void SendCompolited(object sender, SocketAsyncEventArgs e)
        {
            ProcessSend(e);
        }

        private void ProcessSend(SocketAsyncEventArgs async)
        {
            try
            {
                Debug.Log("TCP已发送");
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }
        #endregion
    }
}

你可能感兴趣的:(unity,unity3d,unity,c#)