Unity3D:UDPSocket通信模块

先上接口

using System;

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

接口具体实现

using UnityEngine;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;

namespace YDB.UDPSocket
{

    public class UDP_Socket : IUDPSocket
    {

        //接收数据容量大小
        private const int BufferSize = 1024;
        //Socket
        protected Socket mSocket;

        public UDP_Socket()
        {
            mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        }
        /// 
        /// 关闭Socket连接
        /// 
        public void ShutDown()
        {
            if (mSocket == null)
            {
                return;
            }
            try
            {
                mSocket.Shutdown(SocketShutdown.Both);
                mSocket.Close();
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }
        #region 接收数据

        /// 
        /// 
        /// 
        /// IP
        /// Port
        /// 数据转换,默认Json
        public void ReceivePackage(string receiveIP_str, string receivePort_str, Action<byte[]> action)
        {
            if (string.IsNullOrEmpty(receiveIP_str) || string.IsNullOrEmpty(receivePort_str))
            {
                return;
            }
            if(action == null)
            {
                Debug.LogWarning("回调为空,屁用没有");
            }
            int receivePort = int.Parse(receivePort_str);
            OnStartReceive(receiveIP_str, receivePort,action);
        }
        /// 
        /// 接收数据
        /// 
        /// 
        private void OnStartReceive(string receiveIP_str, int receivePort_int, Action<byte[]> action)
        {
            try
            {
                IPEndPoint receiveIPEndPoint = new IPEndPoint(IPAddress.Parse(receiveIP_str), receivePort_int);
                Debug.Log(string.Format("绑定IP:{0}和Port:{1}", receiveIP_str, receivePort_int));
                mSocket.Bind(receiveIPEndPoint);

                SocketAsyncEventArgs receiveCompletedEventArgs = new SocketAsyncEventArgs();
                receiveCompletedEventArgs.SetBuffer(new byte[BufferSize], 0, BufferSize);
                receiveCompletedEventArgs.Completed += ReceiveCompolited;
                receiveCompletedEventArgs.UserToken = action;

                OnReceive(receiveCompletedEventArgs);
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }
        private void OnReceive(SocketAsyncEventArgs socketAsyncEventArgs)
        {
            Debug.Log("等待接收数据");
            bool result = mSocket.ReceiveAsync(socketAsyncEventArgs);
            if (result == false)
            {
                ProcessReceive(socketAsyncEventArgs);
            }
        }
        /// 
        /// 接收数据完成回调事件
        /// 
        /// 
        /// 
        private void ReceiveCompolited(object sender, SocketAsyncEventArgs e)
        {
            ProcessReceive(e);
        }
        /// 
        /// 处理接收事件
        /// 
        /// 
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
            {
                byte[] receiveDate = new byte[e.BytesTransferred];
                Buffer.BlockCopy(e.Buffer, 0, receiveDate, 0, e.BytesTransferred);

                e.SetBuffer(new byte[BufferSize], 0, BufferSize);

                Action<byte[]> action = e.UserToken as Action<byte[]>;
                action(receiveDate);

                OnReceive(e);
            }
        }
        #endregion
        #region 发送数据

        /// 
        /// 发送数据
        /// 
        /// 
        public void SendPackage(string sendIP_Str, string sendPort_int, byte[] data)
        {
            if (string.IsNullOrEmpty(sendIP_Str) || string.IsNullOrEmpty(sendPort_int))
            {
                return;
            }
            int port = int.Parse(sendPort_int);
            OnSendMessage(sendIP_Str, port, data);
        }
        private void OnSendMessage(string sendIP_Str, int sendPort_int, byte[] data)
        {
            EndPoint sendEndPoint = new IPEndPoint(IPAddress.Parse(sendIP_Str), sendPort_int);
            SocketAsyncEventArgs sendAsyncEventArgs = new SocketAsyncEventArgs();
            sendAsyncEventArgs.UserToken = mSocket;
            sendAsyncEventArgs.RemoteEndPoint = sendEndPoint;
            sendAsyncEventArgs.Completed += SendCompolited;
            sendAsyncEventArgs.SetBuffer(data, 0, data.Length);
            bool result = mSocket.SendToAsync(sendAsyncEventArgs);
            if (result == false)
            {
                ProcessSend(sendAsyncEventArgs);
            }
        }
        /// 
        /// 处理发送后的事件处理
        /// 
        /// 
        private void ProcessSend(SocketAsyncEventArgs mSendAsyncEventArgs)
        {
            if (mSendAsyncEventArgs.SocketError == SocketError.Success)
            {
                Debug.Log("Socket发送成功");
            }
            else
            {
                Debug.LogError("Socket发送失败");
            }
        }

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

}

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