Event handler for a socket session ending in a room. Broadcast
    the user leaving and delete them from the DB.
340581
def finish(request, socket, context):
    
    try:
        user = context["user"]
    except KeyError:
        return
    left = {"action": "leave", "name": user.name, "id": user.id}
    socket.broadcast_channel(left)
    user.delete()
1115920
def handle_quit(self, connection, event):
        
        nickname = self.get_nickname(event)
        self.quit[nickname] = datetime.now()
        del self.joined[nickname]
350291
def close(self):
        
        if self._session is not None:
            try:
                self._session.close()
                self._session = None
            except socket.error as e:
                if e.errno != errno.ECONNRESET:
                    raise
1081095
def close_socket(sock):
    ''''''
    if sock:
        try:
            sock.shutdown(socket.SHUT_RDWR)
        except Exception:
            pass
        try:
            sock.close()
        except Exception:
            pass
1153760
def channels_leave(self, room_id, **kwargs):
        """"""
        return self.__call_api_post('channels.leave', roomId=room_id, kwargs=kwargs)
1172122
def exit(self, result=0, msg=None, *args, **kwargs):
    """"""
    if self._finalizer:
      try:
        self._finalizer()
      except Exception as e:
        try:
          NailgunProtocol.send_stderr(
            self._socket,
            '\nUnexpected exception in finalizer: {!r}\n'.format(e)
          )
        except Exception:
          pass

    try:
      # Write a final message to stderr if present.
      if msg:
        NailgunProtocol.send_stderr(self._socket, msg)

      # Send an Exit chunk with the result.
      NailgunProtocol.send_exit_with_code(self._socket, result)

      # Shutdown the connected socket.
      teardown_socket(self._socket)
    finally:
      super(DaemonExiter, self).exit(result=result, *args, **kwargs)
780089
function end(cb) {
  if(typeof cb === 'function') {
    this.once('disconnect', cb);
  }

  if(this.tcp) {
    // must call destroy to terminate immediately
    this._socket.destroy();
  }else{
    this._socket.end();
  }
}
1071290
def server_close(self):
        
        if self.remove_file:
            try:
                os.remove(self.remove_file)
            except:
                pass
        self.socket.close()
1017669
void terminate( boolean removeFromActiveSession ) {
        if (!isLive()) {
            return;
        }

        isLive = false;

        JcrObservationManager jcrObservationManager = observationManager();
        if (jcrObservationManager != null) {
            jcrObservationManager.removeAllEventListeners();
        }

        cleanLocks();
        if (removeFromActiveSession) this.repository.runningState().removeSession(this);
        this.context.getSecurityContext().logout();
    }
390981
@Override
	public final void onSessionClosed(Session session) {
		this.hsClient.getConnector().removeSession(session);
		HandlerSocketSession hSession = (HandlerSocketSession) session;

		hSession.destroy();
		if (this.hsClient.getConnector().isStarted()
				&& hSession.isAllowReconnect()) {
			this.reconnect(session);
		}
		for (HSClientStateListener listener : this.hsClient
				.getHSClientStateListeners()) {
			listener.onDisconnected(this.hsClient, session
					.getRemoteSocketAddress());
		}
	}
20276
@Override
	public void close() {
		if(userSession == null) {
			return;
		}
		
		try {
			final CloseReason closeReason = new CloseReason(CloseCodes.NORMAL_CLOSURE, "Socket closed");
			userSession.close(closeReason);
		} catch (Throwable e) {
			logger.error("Got exception while closing socket", e);
		}
		
		userSession = null;
	}
754119
function(self) {
    return function(err, avoidThrowError) {
      if (_status === Status.CLOSING || _status === Status.CLOSED) {
        socketErrorDispatchToQueries(err);
        return;
      }
      const mustThrowError = _status !== Status.CONNECTING;
      _status = Status.CLOSING;

      //prevent executing new commands
      _addCommand = _addCommandDisabled;

      if (_socket) {
        _socket.removeAllListeners('error');
        _socket.removeAllListeners('timeout');
        _socket.removeAllListeners('close');
        _socket.removeAllListeners('data');
        if (!_socket.destroyed) _socket.destroy();
        _socket = undefined;
      }
      _status = Status.CLOSED;

      const errorThrownByCmd = socketErrorDispatchToQueries(err);
      if (mustThrowError) {
        if (self.listenerCount('error') > 0) {
          self.emit('error', err);
          self.emit('end');
          _clear();
        } else {
          self.emit('end');
          _clear();
          //error will be thrown if no error listener and no command did throw the exception
          if (!avoidThrowError && !errorThrownByCmd) throw err;
        }
      } else {
        _clear();
      }
    };
  }
382256
def stop_db_session(exc=None):
    """"""
    # print('==> Stop session', type(exc))

    if has_db_session():
        exc_type = None
        tb = None

        if exc:
            exc_type, exc, tb = get_exc_info(exc)

        db_session.__exit__(exc_type, exc, tb)
1197958
def finish(self):
        ""
        log.debug("Session disconnected.")
        try:
            self.sock.shutdown(socket.SHUT_RDWR)
        except: pass
        self.session_end()
143018
static function close($socket,$event=null)
    {
        if($event)
        {
            event_del($event);
            event_free($event);
        }
        fclose($socket);
    }
914303
function socketOnClose() {
  const websocket = this[kWebSocket];

  this.removeListener('close', socketOnClose);
  this.removeListener('end', socketOnEnd);

  websocket.readyState = WebSocket.CLOSING;

  //
  // The close frame might not have been received or the `'end'` event emitted,
  // for example, if the socket was destroyed due to an error. Ensure that the
  // `receiver` stream is closed after writing any remaining buffered data to
  // it. If the readable side of the socket is in flowing mode then there is no
  // buffered data as everything has been already written and `readable.read()`
  // will return `null`. If instead, the socket is paused, any possible buffered
  // data will be read as a single chunk and emitted synchronously in a single
  // `'data'` event.
  //
  websocket._socket.read();
  websocket._receiver.end();

  this.removeListener('data', socketOnData);
  this[kWebSocket] = undefined;

  clearTimeout(websocket._closeTimer);

  if (
    websocket._receiver._writableState.finished ||
    websocket._receiver._writableState.errorEmitted
  ) {
    websocket.emitClose();
  } else {
    websocket._receiver.on('error', receiverOnFinish);
    websocket._receiver.on('finish', receiverOnFinish);
  }
}
1201326
def delete_room(room, reason=''):
    """"""

    if room.custom_server:
        return

    def _delete_room(xmpp):
        muc = xmpp.plugin['xep_0045']
        muc.destroy(room.jid, reason=reason)

    current_plugin.logger.info('Deleting room %s', room.jid)
    _execute_xmpp(_delete_room)
    delete_logs(room)