Unity3D:TCPSocket模块

该博客介绍了如何使用C#实现一个TCP服务器,包括`IServerSocket`接口定义,`SocketInfo`类用于保存客户端信息,以及`TCPServer_Socket`类的具体实现。服务器能监听指定IP和端口,接收客户端连接,处理接收和发送数据,并支持关闭操作。代码详细展示了连接建立、数据接收回调和发送数据的完整流程。
摘要由CSDN通过智能技术生成

服务端Socket-
上接口

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

namespace YDB.TCPSocket
{
    public interface IServerSocket
    {
        /// <summary>
        /// 连接并接收数据
        /// </summary>
        void StartAccept(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(byte[] data);
        /// <summary>
        /// 关闭
        /// </summary>
        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);
        }
        /// <summary>
        /// 关闭
        /// </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>
        /// 测试时,不能以127.0.0.1测试
        /// </summary>
        /// <param name="receiveIP_str">IP</param>
        /// <param name="receivePort_str">Port</param>
        /// <param name="messageConverter">数据转换,默认Json</param>
        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);
        }
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="eventArgs"></param>
        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());
            }
        }
        /// <summary>
        /// 接收数据完成回调事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AcceptCompolited(object sender, SocketAsyncEventArgs e)
        {
            ProcessAccept(e);
        }
        /// <summary>
        /// 处理接收事件
        /// </summary>
        /// <param name="e"></param>
        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());
            }
        }

        /// <summary>
        /// 递归接收入口
        /// </summary>
        /// <param name="e"></param>
        private void OnReceive(SocketInfo socketInfo)
        {
            Socket socket = socketInfo.ClientSocket;
            bool result = socket.ReceiveAsync(socketInfo.SocketAsyncEventArgs);
            if (result == false)
            {
                ProcessReceive(socketInfo.SocketAsyncEventArgs);
            }
        }
        /// <summary>
        /// 接收完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReceiveCompleted(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[] 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 发送数据

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data"></param>
        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
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值