Example #1
0
        /// <summary>
        /// 初始化套接字服务管理
        /// </summary>
        /// <param name="addressFamily">地址协议簇 [ipv4或ipv6]</param>
        /// <param name="socketType">套接字类型 [stream或Dgram]</param>
        /// <param name="protocolType">协议类型 [tcp或者udp]</param>
        /// <param name="backlog">同时监听接入连接数 默认为0, 即 并发可监听数</param>
        /// <param name="socketInvoke">委托回调</param>
        /// <returns>连接是否成功</returns>
        public bool Init(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, int backlog, IRemoteSocket socketInvoke)
        {
            // 绑定委托
            this.socketInvoke = socketInvoke;
            // Allocates one large byte buffer which all I/O operations use a piece of.  This gaurds
            // against memory fragmentation
            bufferManager.InitBuffer();
            for (int i = 0; i < numConnections; i++)
            {
                // preallocate pool of System.Net.Sockets.SocketAsyncEventArgs objects
                // Pre -allocate a set of reusable System.Net.Sockets.SocketAsyncEventArgs
                System.Net.Sockets.SocketAsyncEventArgs readWriteEventArg = new System.Net.Sockets.SocketAsyncEventArgs();
                readWriteEventArg.Completed += new EventHandler <System.Net.Sockets.SocketAsyncEventArgs>(IO_Completed);
                // 如果是报文结构则 初始化终端节点
                if (socketType == SocketType.Stream)
                {
                    RemoteConnection remoteClient = new RemoteConnection(this, socketInvoke);
                    readWriteEventArg.UserToken    = remoteClient;
                    remoteClient.readWriteEventArg = readWriteEventArg;
                }
                else
                {
                    readWriteEventArg.RemoteEndPoint = serverSocket.endPoint;
                }
                // assign a byte buffer from the buffer pool to the SocketAsyncEventArg object
                bufferManager.SetBuffer(readWriteEventArg);
                // add SocketAsyncEventArg to the pool
                readWritePool.Enqueue(readWriteEventArg);
            }
            // 启动服务
            bool bSuccess = serverSocket.ConnectAsServer(addressFamily, socketType, protocolType, backlog);

            StartServer();
            // Log.Info("Init Sever Connecting!");
            return(bSuccess);
        }
Example #2
0
 /// <summary>
 /// 构造函数 tcp
 /// <para>正式调用还需执行Init()</para>
 /// </summary>
 internal RemoteConnection(ServerSocket service, IRemoteSocket socketInvoke)
 {
     socketSvrMgr      = service;
     this.socketInvoke = socketInvoke;
 }