IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> Unity3D:TCPSocket模块 -> 正文阅读

[游戏开发]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
    {
        /// <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
    }
}

  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2022-04-15 00:35:02  更:2022-04-15 00:35:33 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年1日历 -2025/1/16 21:04:09-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码