/// <summary> /// 连线事件 /// </summary> /// <param name="pConnection"></param> internal void SocketConnectedEvent(ConnectionManage pConnection) { if (pConnection.Active) { this._SocketService.OnConnected(new SocketEventArgs(pConnection)); } }
/// <summary> /// Socket异常 /// </summary> /// <param name="ex">异常信息</param> internal void SocketExceptionEvent(ConnectionManage pConnection, Exception ex, bool bForceEvent) { if (bForceEvent || pConnection.Active) { this._SocketService.OnException(new SocketEventArgs(pConnection, ex)); } }
internal void ReConnect(bool bResetAttempts, ConnectionManage pConnection, Exception pException) { if (!this.Disposed) { if (bResetAttempts) { this.iCurrentCount = 0; } if (this._iAttemptCount > 0) { if (this.iCurrentCount < this._iAttemptCount) { this.Service.RemoveSocketConnection(pConnection); this.Service.StopConnections(ref pConnection); this.pReConnectTimer.Change(this._iIdleInterval, this._iIdleInterval); } else { this.CreatorStop(); this.Service.SocketExceptionEvent(pConnection, new ArgumentException("尝试连接次数已达到最大值:", "尝试连接次数为【" + this._iAttemptCount.ToString() + "】次"), true); } } } else { if ((pConnection != null) && (pException != null)) { this.Service.SocketExceptionEvent(pConnection, pException, true); } } }
/// <summary> /// 发送事件 /// </summary> /// <param name="pConnection"></param> /// <param name="pBuffer"></param> private void SocketSentEvent(ConnectionManage pConnection, byte[] pBuffer) { if (pConnection.Active) { this._SocketService.OnSent(new MessageEventArgs(pConnection, pBuffer)); } }
internal void SocketAcceptCallback(IAsyncResult ar) { if (!this.Disposed) { Socket pAcceptedSocket = null; SocketListener pListener = null; ConnectionManage pConnection = null; try { pListener = (SocketListener)ar.AsyncState; pAcceptedSocket = pListener.CurrentSocket.EndAccept(ar); pAcceptedSocket.ReceiveBufferSize = this.Service.SocketBufferSize; pAcceptedSocket.SendBufferSize = this.Service.SocketBufferSize; pConnection = new ServerConnect(pAcceptedSocket, pListener, this.Service); pConnection.Active = true; this.Service.AddConnection(pConnection); ThreadPool.QueueUserWorkItem(new WaitCallback(this.Initialize), pConnection); } catch (Exception ex) { this.Service.SocketExceptionEvent(pConnection, ex); } finally { pListener.CurrentSocket.BeginAccept(new AsyncCallback(SocketAcceptCallback), pListener); } } }
internal void StopConnections(ref ConnectionManage pConnection) { if (pConnection != null) { pConnection.Dispose(); pConnection = null; } }
internal override void SendTo(ConnectionManage pConnectionManage, byte[] pBuffer) { if (!this.Disposed) { //this.SendTo(pConnectionManage, pBuffer); this.SocketSend(pConnectionManage, pBuffer); } }
/// <summary> /// 初始化连接 /// </summary> /// <param name="pState"></param> protected virtual void Initialize(object pState) { //判断对象有效 if (!this.Disposed) { ConnectionManage pConnection = (ConnectionManage)pState; this._pService.SocketConnectedEvent(pConnection); } }
internal override ConnectionManage GetConnection(string strSession) { ConnectionManage pConnectionManage = null; if (!Disposed) { pConnectionManage = this.GetConnections(strSession); } return(pConnectionManage); }
/// <summary> /// 断线处理 - ***** /// </summary> /// <param name="state"></param> private void DisconnectProcessing(object state) { if (!this.Disposed) { bool bCallDisconnect = false; SocketEventArgs pSocketEventArgs = null; ConnectionManage pConnection = null; IAsyncResult AsyncResult = null; try { if (state is SocketEventArgs) { //----- NT5 / Win2000! pSocketEventArgs = (SocketEventArgs)state; bCallDisconnect = false; } else { //----- NT5 / WinXP and later! AsyncResult = (IAsyncResult)state; pSocketEventArgs = (SocketEventArgs)AsyncResult.AsyncState; bCallDisconnect = true; } pConnection = (ConnectionManage)pSocketEventArgs.Connection; if (pConnection.Active) { if (bCallDisconnect) { pConnection.CurrentSocket.EndDisconnect(AsyncResult); } lock (pConnection.ActiveLock) { pConnection.Active = false; pConnection.CurrentSocket.Close(); } this.SocketDisconnectEvent(pSocketEventArgs); } this.RemoveSocketConnection(pConnection); this.StopConnections(ref pConnection); } catch (Exception ex) { this.SocketExceptionEvent(pConnection, ex); } } }
/// <summary> /// 数据发送方法 /// </summary> /// <param name="pConnection"></param> /// <param name="pBuffer"></param> internal void SocketSend(ConnectionManage pConnection, byte[] pBuffer) { //判断对象有效 if (!this.Disposed) { try { //判断连接有效 if (pConnection.Active) { pConnection.LastAction = DateTime.Now; //创建发送缓冲区 SocketBuffer pSendBuffer = SocketBuffer.GetPacketBuffer(this._eCompression, ref pBuffer); //为当前连接加锁 lock (pConnection.SendQueue) { //判断发送状态 if (pConnection.SendState) { //正在发送中 pConnection.SendQueue.Enqueue(pSendBuffer); } else { //更改发送状态 pConnection.SendState = true; //发送数据流 if (pConnection.CurrentStream != null) { pConnection.CurrentStream.BeginWrite(pSendBuffer.ContentBuffer, pSendBuffer.OffSet, pSendBuffer.Remaining, new AsyncCallback(SendCallback), new SocketDataCallback(pConnection, pSendBuffer)); } else { pConnection.CurrentSocket.BeginSend(pSendBuffer.ContentBuffer, pSendBuffer.OffSet, pSendBuffer.Remaining, SocketFlags.None, new AsyncCallback(SendCallback), new SocketDataCallback(pConnection, pSendBuffer)); } } //end if } //end lock } //end if } catch (Exception ex) { this.SocketExceptionEvent(pConnection, ex); } //end try...catch... } //end if }
internal void AddConnection(ConnectionManage pConnection) { if (!this.Disposed) { this.pSocketConnectionsLock.AcquireWriterLock(Timeout.Infinite); try { this.arrConnections.Add(pConnection.Session, pConnection); } finally { this.pSocketConnectionsLock.ReleaseWriterLock(); } } }
/// <summary> /// 数据接收方法 /// </summary> /// <param name="pConnection"></param> internal void SocketRecive(ConnectionManage pConnection) { //判断对象有效 if (!this.Disposed) { try { //判断连接有效 if (pConnection.Active) { //为当前连接加锁 lock (pConnection.ReciveLock) { //读取接收到的数据 if (pConnection.ReciveState) { if (pConnection.ReadCount == 0) { //创建接收缓冲区 SocketBuffer pReciveBuffer = new SocketBuffer(this.SocketBufferSize); if (pConnection.CurrentStream != null) { //从SSL Stream读取数据 pConnection.CurrentStream.BeginRead(pReciveBuffer.ContentBuffer, pReciveBuffer.OffSet, pReciveBuffer.Remaining, new AsyncCallback(ReciveCallback), new SocketDataCallback(pConnection, pReciveBuffer)); } else { //从Socket Stream读取数据 pConnection.CurrentSocket.BeginReceive(pReciveBuffer.ContentBuffer, pReciveBuffer.OffSet, pReciveBuffer.Remaining, SocketFlags.None, new AsyncCallback(ReciveCallback), new SocketDataCallback(pConnection, pReciveBuffer)); } //end if } //end if ReadCount pConnection.ReadCount++; } //end if } //end lock } } catch (Exception ex) { this.SocketExceptionEvent(pConnection, ex); } //end try...catch... } // end if }
internal ConnectionManage GetConnections(string strSession) { ConnectionManage pConnectionItem = null; if (!this.Disposed) { this.pSocketConnectionsLock.AcquireReaderLock(Timeout.Infinite); try { pConnectionItem = this.arrConnections[strSession]; } finally { this.pSocketConnectionsLock.ReleaseReaderLock(); } } return(pConnectionItem); }
internal ConnectionManage[] GetConnections() { ConnectionManage[] pConnectionItems = null; if (!this.Disposed) { this.pSocketConnectionsLock.AcquireReaderLock(Timeout.Infinite); try { pConnectionItems = new ConnectionManage[this.arrConnections.Count]; this.arrConnections.Values.CopyTo(pConnectionItems, 0); } finally { this.pSocketConnectionsLock.ReleaseReaderLock(); } } return(pConnectionItems); }
/// <summary> /// 接收事件 /// </summary> /// <param name="pConnection"></param> /// <param name="pBuffer"></param> /// <param name="bCanEnqueue"></param> private void SocketReceivedEvent(ConnectionManage pConnection, byte[] pBuffer, bool bCanEnqueue) { if (pConnection.Active) { if (!bCanEnqueue) { lock (pConnection.ReciveLock) { pConnection.ReciveState = false; } } this._SocketService.OnReceived(new MessageEventArgs(pConnection, pBuffer)); if (!bCanEnqueue) { lock (pConnection.ReciveLock) { pConnection.ReciveState = true; } } } }
internal void ConnectCallback(IAsyncResult ar) { if (!this.Disposed) { ConnectionManage pConnection = null; SocketConnector pConnector = null; try { pConnector = (SocketConnector)ar.AsyncState; pConnection = new ClientConnect(pConnector.CurrentSocket, this, this.Service); pConnector.CurrentSocket.EndConnect(ar); pConnector.CurrentSocket.ReceiveBufferSize = this.Service.SocketBufferSize; pConnector.CurrentSocket.SendBufferSize = this.Service.SocketBufferSize; pConnection.Active = true; this.Service.AddConnection(pConnection); this.Initialize(pConnection); } catch (Exception ex) { if (ex is SocketException) { this.iCurrentCount++; this.ReConnect(false, pConnection, ex); } else { this.Service.SocketExceptionEvent(pConnection, ex); } } } }
/// <summary> /// 断线方法 - ***** /// </summary> /// <param name="pConnection"></param> /// <param name="DisconnectException"></param> internal void SocketDisconnect(ConnectionManage pConnection) { //判断对象有效 if (!this.Disposed) { SocketEventArgs pSocketEventArgs = new SocketEventArgs(pConnection, false); if (pConnection.Active) { try { //判断操作系统版本号 if ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1)) { //--- NT5 / WinXP and later! pConnection.CurrentSocket.BeginDisconnect(false, new AsyncCallback(DisconnectCallback), pSocketEventArgs); } else { //---- NT5 / Win2000! ThreadPool.QueueUserWorkItem(new WaitCallback(DisconnectProcessing), pSocketEventArgs); }//end Version if...else... } catch (Exception ex) { this.SocketExceptionEvent(pConnection, ex); } } else { this.RemoveSocketConnection(pConnection); this.StopConnections(ref pConnection); } }//end if }
internal void RemoveSocketConnection(ConnectionManage pConnection) { if (!this.Disposed) { if (pConnection != null) { this.pSocketConnectionsLock.AcquireWriterLock(Timeout.Infinite); try { this.arrConnections.Remove(pConnection.Session); } finally { this.pSocketConnectionsLock.ReleaseWriterLock(); if (this.arrConnections.Count <= 0) { this.pConnectionsResetEvent.Set(); } } } } }
/// <summary> /// 构造函数 /// </summary> /// <param name="pConnectionManage"></param> /// <param name="pBuffer"></param> public SocketDataCallback(ConnectionManage pConnection, object pSocketBuffer) { this._pConnection = pConnection; this._pSocketBuffer = pSocketBuffer; }
internal override void SendTo(ConnectionManage pConnectionManage, byte[] pBuffer) { }
/// <summary> /// 数据处理 - *** /// </summary> /// <param name="pSocketDataCallback"></param> /// <param name="iBytesCount"></param> private void BufferProcessing(SocketDataCallback pSocketDataCallback, int iBytesCount, ref bool bReadSocket) { byte[] pDataBuffer = null; ConnectionManage pConnection = pSocketDataCallback.Connection; SocketBuffer pReciveBuffer = (SocketBuffer)pSocketDataCallback.SocketBuffer; pConnection.LastAction = DateTime.Now; //Console.WriteLine(iBytesCount); pReciveBuffer.OffSet += iBytesCount; //--- 改进的地方 //读取方向开关 bool bFromBuffer = false; bool bFromSocket = false; //确定数据体大小以及读取方向 do { //判断当前Buffer大小 if (pReciveBuffer.OffSet > SocketConstant.MAX_SOCKETHEAD_SIZE) { //判断数据体是否填充 if (pReciveBuffer.BodySize == 0) { SocketHead pPacketHead = new SocketHead(pReciveBuffer.ContentBuffer); pPacketHead.ExtractInfo(); pReciveBuffer.BodySize = pPacketHead.BodyLength; pReciveBuffer.Compression = pPacketHead.Compression; pReciveBuffer.CRCBuffer = pPacketHead.CRCValue; }//end if pReciveBuffer.BodySize //Socket Packet 大小 int iBodySize = pReciveBuffer.BodySize + SocketConstant.MAX_SOCKETHEAD_SIZE; //数据读取结束 if (iBodySize == pReciveBuffer.OffSet) { pDataBuffer = pReciveBuffer.GetRawBuffer(SocketConstant.MAX_SOCKETHEAD_SIZE, iBodySize); bFromBuffer = false; bFromSocket = false; } else { //从Buffer读取数据 if (iBodySize < pReciveBuffer.OffSet) { pDataBuffer = pReciveBuffer.GetRawBuffer(SocketConstant.MAX_SOCKETHEAD_SIZE, iBodySize); bFromBuffer = true; bFromSocket = false; this.SocketReceivedEvent(pConnection, pDataBuffer, false); } else { //从Socket读取数据 if (iBodySize > pReciveBuffer.OffSet) { //更改Buffer大小至Socket Packet大小 if (iBodySize > pReciveBuffer.CurrentSize) { pReciveBuffer.Resize(iBodySize); } bFromBuffer = false; bFromSocket = true; } } }//end if (iBodySize == pReciveBuffer.OffSet) } else { if (pReciveBuffer.Remaining < SocketConstant.MAX_SOCKETHEAD_SIZE) { pReciveBuffer.Resize(pReciveBuffer.CurrentSize + SocketConstant.MAX_SOCKETHEAD_SIZE); } bFromBuffer = false; bFromSocket = true; }//end if (pReciveBuffer.OffSet > SocketConstant.MAX_SOCKETHEAD_SIZE) } while (bFromBuffer); //从Socket读取数据 if (bFromSocket) { if (pConnection.Active) { if (pConnection.CurrentStream != null) { //从SSL Stream读取数据 pConnection.CurrentStream.BeginRead(pReciveBuffer.ContentBuffer, pReciveBuffer.OffSet, pReciveBuffer.Remaining, new AsyncCallback(ReciveCallback), new SocketDataCallback(pConnection, pReciveBuffer)); } else { //从Socket Stream读取数据 pConnection.CurrentSocket.BeginReceive(pReciveBuffer.ContentBuffer, pReciveBuffer.OffSet, pReciveBuffer.Remaining, SocketFlags.None, new AsyncCallback(ReciveCallback), new SocketDataCallback(pConnection, pReciveBuffer)); } } } if (null != pDataBuffer) { pDataBuffer = CompressionUtilise.DeCompressionData(pReciveBuffer.Compression, pDataBuffer); this.SocketReceivedEvent(pConnection, pDataBuffer, true); }//end pDataBuffer if...else... bReadSocket = bFromSocket; pReciveBuffer = null; pSocketDataCallback = null; }
/// <summary> /// 接收数据处理 -- *** /// </summary> /// <param name="state"></param> private void ReciveProcessing(object state) { if (!this.Disposed) { ConnectionManage pConnection = null; IAsyncResult AsyncResult = (IAsyncResult)state; try { SocketDataCallback pCallbackBuffer = (SocketDataCallback)AsyncResult.AsyncState; pConnection = pCallbackBuffer.Connection; if (pConnection.Active) { int iReadBytes = 0; if (pConnection.CurrentStream != null) { iReadBytes = pConnection.CurrentStream.EndRead(AsyncResult); } else { iReadBytes = pConnection.CurrentSocket.EndReceive(AsyncResult); }//end CurrentStream if...else... if (iReadBytes > 0) { bool bReadSocket = false; this.BufferProcessing(pCallbackBuffer, iReadBytes, ref bReadSocket); if (!bReadSocket) { //检索队列 lock (pConnection.ReciveLock) { pConnection.ReadCount--; if (pConnection.ReadCount > 0) { SocketBuffer pNextBuffer = new SocketBuffer(this.SocketBufferSize); if (pConnection.CurrentStream != null) { //从SSL Stream读取数据 pConnection.CurrentStream.BeginRead(pNextBuffer.ContentBuffer, pNextBuffer.OffSet, pNextBuffer.Remaining, new AsyncCallback(ReciveCallback), new SocketDataCallback(pConnection, pNextBuffer)); } else { //从Socket Stream读取数据 pConnection.CurrentSocket.BeginReceive(pNextBuffer.ContentBuffer, pNextBuffer.OffSet, pNextBuffer.Remaining, SocketFlags.None, new AsyncCallback(ReciveCallback), new SocketDataCallback(pConnection, pNextBuffer)); } //end CurrentStream if...else... } //end ReadCount if...else... } //end lock } } else { pConnection.OnDisconnect(); } //end iReadBytes if...else... } //end Active if...else... } catch (Exception ex) { this.SocketExceptionEvent(pConnection, ex); }//end try...catch... } }
/// <summary> /// 发送数据处理 /// </summary> /// <param name="state"></param> private void SendProcessing(object pSendState) { if (!this.Disposed) { bool bCanReadQueue = false; SocketBuffer pSendBuffer = null; ConnectionManage pConnection = null; IAsyncResult AsyncResult = (IAsyncResult)pSendState; try { SocketDataCallback pCallbackBuffer = (SocketDataCallback)AsyncResult.AsyncState; pConnection = pCallbackBuffer.Connection; pSendBuffer = (SocketBuffer)pCallbackBuffer.SocketBuffer; if (pConnection.Active) { if (pConnection.CurrentStream != null) { pConnection.CurrentStream.EndWrite(AsyncResult); this.SocketSend(pConnection, pSendBuffer.RawBuffer); bCanReadQueue = true; } else { int iWriteBytes = pConnection.CurrentSocket.EndSend(AsyncResult); if (iWriteBytes < pSendBuffer.Remaining) { bCanReadQueue = false; pSendBuffer.OffSet += iWriteBytes; pConnection.CurrentSocket.BeginSend(pSendBuffer.ContentBuffer, pSendBuffer.OffSet, pSendBuffer.Remaining, SocketFlags.None, new AsyncCallback(SendCallback), pCallbackBuffer); } else { this.SocketSentEvent(pConnection, pSendBuffer.RawBuffer); bCanReadQueue = true; } }//end CurrentStream if...else... if (bCanReadQueue) { pSendBuffer = null; pCallbackBuffer = null; lock (pConnection.SendQueue) { if (pConnection.SendQueue.Count > 0) { SocketBuffer pQueueBuffer = pConnection.SendQueue.Dequeue(); //发送数据流 if (pConnection.CurrentStream != null) { pConnection.CurrentStream.BeginWrite(pQueueBuffer.ContentBuffer, pQueueBuffer.OffSet, pQueueBuffer.Remaining, new AsyncCallback(SendCallback), new SocketDataCallback(pConnection, pQueueBuffer)); } else { pConnection.CurrentSocket.BeginSend(pQueueBuffer.ContentBuffer, pQueueBuffer.OffSet, pQueueBuffer.Remaining, SocketFlags.None, new AsyncCallback(SendCallback), new SocketDataCallback(pConnection, pQueueBuffer)); } } else { pConnection.SendState = false; } } //lock SendQueue } //end bCanReadQueue if...else... } //end Active if...else... } catch (Exception ex) { this.SocketExceptionEvent(pConnection, ex); } } }
protected override void Initialize(object pState) { ConnectionManage pConnectionManage = (ConnectionManage)pState; base.Initialize(pConnectionManage); }
/// <summary> /// Socket异常 /// </summary> /// <param name="ex">异常信息</param> internal void SocketExceptionEvent(ConnectionManage pConnection, Exception ex) { this.SocketExceptionEvent(pConnection, ex, false); }
internal abstract void SendTo(ConnectionManage pConnectionManage, byte[] pBuffer);