大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > C#技巧 > 写自己的Socket框架(一)

写自己的Socket框架(一)(2)

关键词:Socket框架  阅读(3572) 赞(11)

[摘要]本文是对写自己的Socket框架(一)的讲解,对学习C#编程技术有所帮助,与大家分享。

4、入完队列,就要开始从链接池子里面分配资源了,你也可以不做链接池,在每次请求过来的时候去实例化一个链接,然后将这个链接入池,我的做法是在程序初始化的时候就分配好一定的资源,代码如下:

public class SocketConnectionPool : IDisposable
    {
        private ServerConfig _serverConfig;

        public IAppServer AppServer;

        private ConcurrentStack<SocketConnection> _connectPool;

        private long connect_id = 0;
        private byte[] _buffer;
        private readonly object _syncObject = new object();

        private SocketConnectionQueue _queue;

        public Action<System.Net.Sockets.Socket, SocketConnection> Connected;

        public long GenerateId()
        {
            if (connect_id == long.MaxValue)
            {
                connect_id = 0;
            }
            connect_id++;
            return connect_id;
        }

        public SocketConnectionPool(IAppServer server)
        {
            this.AppServer = server;
            this._serverConfig = server.AppConfig;

        }

        public void Init()
        {
            var connects = new List<SocketConnection>(this._serverConfig.MaxConnectionNumber);
            _buffer = new byte[this._serverConfig.BufferSize];
            SocketAsyncEventArgs arg;
            for (var i = 0; i < this._serverConfig.MaxConnectionNumber; i++)
            {
                arg = new SocketAsyncEventArgs();
                arg.SetBuffer(_buffer, 0, _buffer.Length);
                connects.Add(new SocketConnection(arg, this));
            }
            _connectPool = new ConcurrentStack<SocketConnection>(connects);
            if (_queue == null)
            {
                _queue = new SocketConnectionQueue();
            }
            
            _queue.Connected = OnConnected;
        }

        public void Push(System.Net.Sockets.Socket socket)
        {
            SocketProxy proxy = new SocketProxy()
            {
                Client = socket
            };
            _queue.Push(proxy);
        }

        public void OnConnected(SocketProxy proxy)
        {
            //如果发现队列里面的链接,在Timeout时间内,都没有分配到资源,则关掉链接并丢弃。
            int timeout = (int)(DateTime.Now - proxy.Timeout).TotalSeconds;
            if (timeout >= this._serverConfig.Timeout)
            {
                proxy.Client.Close();
                return;
            }
            else
            {
                //没有分配到资源重新入列。
                SocketConnection connect = this.GetConnectionFromPool();
                if (connect == null)
                {
                    _queue.Push(proxy);
                }
                else
                {
                    if (this.Connected != null)
                    {
                        this.Connected(proxy.Client, connect);
                    }
                }
            }
        }

        /// <summary>
        /// 从链接池去取链接(LIFO)
        /// </summary>
        /// <returns></returns>
        public SocketConnection GetConnectionFromPool()
        {
            //_queue.Push();
            SocketConnection connect;
            if (!_connectPool.TryPop(out connect))
            {
                return null;
            }
            lock (_syncObject)
            {
                long connect_id = this.GenerateId();
                connect.ConnectId = connect_id;
            }
            return connect;
        }
        /// <summary>
        /// 释放链接,并放回链接池
        /// </summary>
        /// <param name="connect"></param>
        public void ReleaseConnection(SocketConnection connect)
        {
            _connectPool.Push(connect);
            LogHelper.Debug(connect.ConnectId + "放回ConnectPool");
        }

        public void Dispose()
        {
            _queue.Dispose();
        }
    }

在Init()里面初始化了很多个SocketConnection,这个就是我们用来管理具体的单个链接的class,代码如下:

public class SocketConnection
    {
        public SocketFlag Flag { get; private set; }
        
        public SocketConnectionPool Pool { get { return _pool; } private set { } }
        private SocketConnectionPool _pool;

        public SocketAsyncEventArgs RecevieEventArgs { get; set; }

        public long ConnectId { get; set; }

        public SocketConnection()
        {
            this.Flag = SocketFlag.Error;
        }

        public SocketConnection(SocketAsyncEventArgs args, SocketConnectionPool pool)
        {
            RecevieEventArgs = args;
            RecevieEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArgs_Completed);
            
            this.Flag = SocketFlag.Busy;
            this._pool = pool;
        }

        void SocketEventArgs_Completed(object sender, SocketAsyncEventArgs e)
        {
            var socketSession = e.UserToken as SocketSession;
            if (socketSession == null)
            {
                this.Flag = SocketFlag.Error;
                this.Close();
                return;
            }

            switch (e.LastOperation)
            { 
                case SocketAsyncOperation.Receive:
                    socketSession.ReceiveData(e);
                    break;
                default:
                    break;
            }
        }

        public void Initialise(SocketSession session)
        {
            this.RecevieEventArgs.UserToken = session;
            this.Flag = SocketFlag.Busy;

            session.Closed += () =>
            {
                this.Close();
            };
        }

        public void Reset()
        {
            //ConnectId = 0;
            this.RecevieEventArgs.UserToken = null;
            this.Flag = SocketFlag.Idle;
        }

        private void Close()
        {
            this.Reset();
            LogHelper.Debug(ConnectId + " reset");
            this._pool.ReleaseConnection(this);
        }
    }
«上一页12下一页»


相关评论