Unity3D:UDPSocket通信模块

先上接口

using System;

namespace YDB.UDPSocket
{
    public interface IUDPSocket
    {
        /// <summary>
        /// 连接并接收数据
        /// </summary>
        void ReceivePackage(string receiveIP_str, string receivePort_str, Action<byte[]> action);
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sendIP_Str"></param>
        /// <param name="sendPort_int"></param>
        /// <param name="data"></param>
        void SendPackage(string sendIP_Str, string sendPort_int, byte[] data);
        /// <summary>
        /// 关闭
        /// </summary>
        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);
        }
        /// <summary>
        /// 关闭Socket连接
        /// </summary>
        public void ShutDown()
        {
            if (mSocket == null)
            {
                return;
            }
            try
            {
                mSocket.Shutdown(SocketShutdown.Both);
                mSocket.Close();
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }
        #region 接收数据

        /// <summary>
        /// 
        /// </summary>
        /// <param name="receiveIP_str">IP</param>
        /// <param name="receivePort_str">Port</param>
        /// <param name="messageConverter">数据转换,默认Json</param>
        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);
        }
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="eventArgs"></param>
        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);
            }
        }
        /// <summary>
        /// 接收数据完成回调事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReceiveCompolited(object sender, SocketAsyncEventArgs e)
        {
            ProcessReceive(e);
        }
        /// <summary>
        /// 处理接收事件
        /// </summary>
        /// <param name="e"></param>
        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 发送数据

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="message"></param>
        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);
            }
        }
        /// <summary>
        /// 处理发送后的事件处理
        /// </summary>
        /// <param name="mSendAsyncEventArgs"></param>
        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
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值