void sh_BinaryFrame(object sender, Events.BinaryFrameEventArgs e)
        {
            WebSocketHandlerService sh = sender as WebSocketHandlerService;

            if (sh != null)
            {
                EventsHelper.Fire(Received, this, new DataEventArgs(e.Payload, sh.ConnectionId));
            }
        }
        private void sh_ConnectionOpened(object sender, EventArgs e)
        {
            WebSocketHandlerService sh = sender as WebSocketHandlerService;

            if (sh != null)
            {
                EventsHelper.Fire(Connected, this, new ConnectionEventArgs(sh.ConnectionId, 0, "OK"));
            }
        }
        private void sh_TextFrame(object sender, Events.TextFrameEventArgs e)
        {
            WebSocketHandlerService sh = sender as WebSocketHandlerService;

            if (sh != null)
            {
                EventsHelper.Fire(Received, this, new DataEventArgs(e.Text, sh.ConnectionId));
            }
        }
        private void sh_ConnectionClose(object sender, Events.ConnectionCloseEventArgs e)
        {
            WebSocketHandlerService sh = sender as WebSocketHandlerService;

            if (sh != null)
            {
                DeleteClientConnection(sh.ConnectionId);
            }


            if (ClientDisconnected != null)
            {
                ClientDisconnected(this, new ConnectionEventArgs(sh.ConnectionId, (int)e.Code, e.Reason));
            }
        }
        private void sh_WebSocketHandShakeSent(object sender, EventArgs e)
        {
            WebSocketHandlerService sh = sender as WebSocketHandlerService;

            if (sh == null)
            {
                return;
            }

            int tmpConnId;

            lock (m_DisconnectedConnections)
            {
                if (m_DisconnectedConnections.Count > 0)
                {
                    // Assign old disconnecetd connection id to a new one
                    tmpConnId = m_DisconnectedConnections[0];
                    m_DisconnectedConnections.RemoveAt(0);
                }
                else
                {
                    tmpConnId = Interlocked.Increment(ref m_clientCount);
                }
            }

            sh.ConnectionId      = tmpConnId;
            sh.ConnectionOpened += sh_ConnectionOpened;
            sh.TextFrame        += sh_TextFrame;
            sh.TextMultiFrame   += sh_TextMultiFrame;
            sh.ConnectionClose  += sh_ConnectionClose;
            sh.BinaryFrame      += sh_BinaryFrame;
            sh.BinaryMultiFrame += sh_BinaryMultiFrame;

            // Add the workerSocket handler reference to our ArrayList
            lock (m_workerSocketList)
            {
                m_workerSocketList.Add(sh.ConnectionId, sh);
            }

            _logger.DebugFormat("Connected for client {0} ", tmpConnId);
            if (Connected != null)
            {
                Connected(this, new ConnectionEventArgs(sh.ConnectionId, 0, "OK"));
            }
        }
 private void DeleteClientConnection(int connectionId)
 {
     lock (m_workerSocketList)
     {
         if (m_workerSocketList.ContainsKey(connectionId))
         {
             WebSocketHandlerService ws = m_workerSocketList[connectionId];
             m_workerSocketList.Remove(connectionId);
             lock (m_DisconnectedConnections)
             {
                 if (!m_DisconnectedConnections.Contains(connectionId))
                 {
                     m_DisconnectedConnections.Add(connectionId);
                 }
             }
             ws.Dispose();
         }
     }
 }
        public void Send(int connectionId, byte[] data)
        {
            WebSocketHandlerService sh = null;

            lock (m_workerSocketList)
            {
                if (m_workerSocketList.ContainsKey(connectionId))
                {
                    sh = m_workerSocketList[connectionId];
                }
            }

            if (sh != null)
            {
                sh.Send(data);
            }
            else
            {
                // remove from socket list --this should not happen so log it
                DeleteClientConnection(connectionId);
                OnError(this, new ErrorEventArgs(-1, string.Format("Connection not available for Id: {0}", connectionId)));
            }
        }
        private void HandleAsyncConnection(IAsyncResult res)
        {
            try
            {
                if (_isDisposed)
                {
                    return;
                }

                // this worker thread stays alive until either of the following happens:
                // Client sends a close conection request OR
                // An unhandled exception is thrown OR
                // The server is disposed
                try
                {
                    //using (
                    TcpClient tcpClient = _mainSocket.EndAcceptTcpClient(res);
                    //)
                    {
                        if (ConnectionCount < MaxConnections)
                        {
                            StartAccept();
                        }
                        _logger.Info("WebSocketDaemonSB opened client connection");

                        // get a secure or insecure stream
                        Stream stream = GetStream(tcpClient);

                        // extract the connection details and use those details to build a connection
                        ConnectionDetails connectionDetails = GetConnectionDetails(stream, tcpClient);
                        //using (
                        IService service = _serviceFactory.CreateInstance(connectionDetails, true);
                        //  )
                        {
                            // respond to the http request.
                            // Take a look at the WebSocketConnection or HttpConnection classes

                            WebSocketHandlerService sh = service as WebSocketHandlerService;
                            if (sh != null)
                            {
                                sh.ChannelParameters       = _channelParameters;
                                sh.WebSocketHandShakeSent += sh_WebSocketHandShakeSent;
                            }

                            service.Respond();

                            _logger.DebugFormat("Service responded {0} ", connectionDetails.ConnectionType);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error("Error in HandleAsyncConnection", ex);
                }
            }
            catch (ObjectDisposedException)
            {
                // do nothing. This will be thrown if the Listener has been stopped
            }
            catch (Exception ex)
            {
                _logger.Error("Error in HandleAsyncConnection", ex);
            }
        }