Equivalent to socket.accept(), but transforms the socket into a
        websocket instance and sends a server handshake (after receiving a
        client handshake). Note that the handshake may raise a HandshakeError
        exception.
7834
def accept(self):
        
        sock, address = self.sock.accept()
        wsock = websocket(sock)
        wsock.secure = self.secure
        ServerHandshake(wsock).perform(self)
        wsock.handshake_sent = True
        return wsock, address
539115
public static CheckedSocket check(SocketFace socket)
        throws SocketException
    {
        if (socket instanceof CheckedSocket) {
            return (CheckedSocket)socket;
        }
        else {
            return new CheckedSocket(socket);
        }
    }
62760
def accept(self):
        
        fd, addr = self._accept()
        sock = socket(self.family, self.type, self.proto, fileno=fd)
        # Issue #7995: if no default timeout is set and the listening
        # socket had a (non-zero) timeout, force the new socket in blocking
        # mode to override platform-specific socket flags inheritance.
        if getdefaulttimeout() is None and self.gettimeout():
            sock.setblocking(True)
        return sock, addr
170921
function() {
        try {
          if (socket && socket.readyState == 1) {
            return;
          }

          socket = new WebSocket(address, []);

          socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
          socketRealTimeStatusInterval = setInterval(function() {
            switch (socket.readyState) {
              case 2:
                onCloseHandler(null);
                break;
              case 3:
                socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
                break;
            }
          }, 5000);

          socket.onopen = function(event) {
            waitForSocketToConnect(function() {
              eventCallback["open"]();
            });
          }

          socket.onmessage = function(event) {
            var messageData = JSON.parse(event.data);
            eventCallback["message"](messageData);

            /**
             * To avoid manually closing socket's connection
             */
            forceCloseSocket = false;

            socketCloseTimeout && clearTimeout(socketCloseTimeout);
            forceCloseTimeout && clearTimeout(forceCloseTimeout);

            socketCloseTimeout = setTimeout(function() {
              /**
               * If message's type is not 5, socket won't get any acknowledge packet,therefore
               * you may think that connection has been closed and you would force socket
               * to close, but before that you should make sure that connection is actually closed!
               * for that, you must send a ping message and if that message don't get any
               * responses too, you are allowed to manually kill socket connection.
               */
              ping();

              /**
               * We set forceCloseSocket as true so that if your ping's response don't make it
               * you close your socket
               */
              forceCloseSocket = true;

              /**
               * If type of messages are not 5, you won't get ant ACK packets
               * for that being said, we send a ping message to be sure of
               * socket connection's state. The ping message should have an
               * ACK, if not, you're allowed to close your socket after
               * 4 * [connectionCheckTimeout] seconds
               */
              forceCloseTimeout = setTimeout(function() {
                if (forceCloseSocket) {
                  socket.close();
                }
              }, connectionCheckTimeout);

            }, connectionCheckTimeout * 1.5);
          }

          socket.onclose = function(event) {
            onCloseHandler(event);
          }

          socket.onerror = function(event) {
            eventCallback["error"](event);
          }
        } catch (error) {
          eventCallback["customError"]({
            errorCode: 4000,
            errorMessage: "ERROR in WEBSOCKET!",
            errorEvent: error
          });
        }
      }
31060
def socket_closed(self, sock):
        
        while True:
            try:
                if self._poller:
                    with self._lock:
                        self._poller.register(sock, _EVENT_MASK)
                        try:
                            rd = self._poller.poll(0)
                        finally:
                            self._poller.unregister(sock)
                else:
                    rd, _, _ = select.select([sock], [], [], 0)
            except (RuntimeError, KeyError):
                # RuntimeError is raised during a concurrent poll. KeyError
                # is raised by unregister if the socket is not in the poller.
                # These errors should not be possible since we protect the
                # poller with a mutex.
                raise
            except ValueError:
                # ValueError is raised by register/unregister/select if the
                # socket file descriptor is negative or outside the range for
                # select (> 1023).
                return True
            except (_SELECT_ERROR, IOError) as exc:
                if _errno_from_exception(exc) in (errno.EINTR, errno.EAGAIN):
                    continue
                return True
            except Exception:
                # Any other exceptions should be attributed to a closed
                # or invalid socket.
                return True
            return len(rd) > 0
962679
protected void handleHttpRequest(final ChannelHandlerContext channelContext, final HttpRequest request) throws Exception {
        if (isWebSocketsUpgradeRequest( request )) {

            final Handshake handshake = findHandshake( request );

            if (handshake != null) {

                HttpResponse response = handshake.generateResponse( request );

                response.addHeader( Names.UPGRADE, Values.WEBSOCKET );
                response.addHeader( Names.CONNECTION, Values.UPGRADE );

                final ChannelPipeline pipeline = channelContext.getChannel().getPipeline();
                reconfigureUpstream( pipeline, handshake );

                Channel channel = channelContext.getChannel();
                ChannelFuture future = channel.write( response );
                future.addListener( new ChannelFutureListener() {
                    public void operationComplete(ChannelFuture future) throws Exception {
                        reconfigureDownstream( pipeline, handshake );
                        pipeline.replace( ServerHandshakeHandler.this, "websocket-disconnection-negotiator", new WebSocketDisconnectionNegotiator() );
                        forwardConnectEventUpstream( channelContext );
                        decodeHost( channelContext, request );
                        decodeSession( channelContext, request );
                    }
                } );

                return;
            }
        }

        // Send an error page otherwise.
        sendHttpResponse( channelContext, request, new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN ) );
    }
1370428
def socket_send(
        sock,
        msg,
        debug=False):
    
    if IS_PY2:
        sock.send(msg)
    else:
        sock.send(msg.encode())
1257809
private function accept(SocketServer $server, int $cryptoMethod, float $timeout, bool $allowPersistent): \Generator
    {
        yield from $this->log->log(
            Log::INFO,
            'HTTP server listening on %s:%d',
            $server->getAddress(),
            $server->getPort()
        );

        while ($server->isOpen()) {
            try {
                $coroutine = new Coroutine(
                    $this->process(yield from $server->accept(), $cryptoMethod, $timeout, $allowPersistent)
                );
                $coroutine->done(null, $this->onError);
            } catch (Throwable $exception) {
                if ($this->isOpen()) {
                    throw $exception;
                }
            }
        }
    }
560857
def do_handshake(self, timeout):
        ''
        tout = _timeout(timeout)
        if not self._blocking:
            return self._sslobj.do_handshake()

        while 1:
            try:
                return self._sslobj.do_handshake()
            except ssl.SSLError, exc:
                if exc.args[0] == ssl.SSL_ERROR_WANT_READ:
                    self._wait_event(tout.now)
                    continue
                elif exc.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                    self._wait_event(tout.now, write=True)
                    continue
                raise

        self._wait_event(timeout)
        self._sslobj.do_handshake()
23339
def accept
      @socket   = server.accept
      @messages = {}

      @driver = ::WebSocket::Driver.server(self)
      @driver.on(:connect) { |_event| @driver.start }
      @driver.on(:message) do |event|
        command_id = JSON.parse(event.data)['command_id']
        @messages[command_id] = event.data
      end
    end
1334642
def receive_connection():
    
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("localhost", 8080))
    server.listen(1)
    client = server.accept()[0]
    server.close()
    return client
523387
def streamserver_handle(cls, socket, address):
        ''''''
        request = cls.dummy_request()
        request._sock = socket
        server = None
        cls(request, address, server)
1076783
function TcpConnect (socket) {
    this.count ++;    // increment client count inside this server
    socket.uid = "Socket://" + socket.remoteAddress +":" + socket.remotePort;
    socket.controller = this.controller;
    socket.adapter   = this.adapter;
    socket.controller.Debug(4, "N°:%d Server=[%s] Client: [%s]"
             ,this.count,this.uid,socket.uid);            
        
    // attach new device object to client socket
    socket.device = new TcpClient (socket);
    
    // notify adapter that it has a new client device connected
    if (socket.adapter.ClientConnect (socket) === -1) {
        try {socket.end();} catch(e){};
        return;
    }
  
    // send any received data to device parser
    socket.on(this.evtname, function(buffer) {
	    socket.controller.Debug(7, "%s Data=[%s]", socket.device.uid, buffer);
        // call adapter specific method to process messages
        socket.adapter.ParseBuffer(socket, buffer);
    });
    
    // On error close socket
    socket.on('error', function (err) {
        socket.controller.Debug(3, "%s ERROR=[%s]", socket.device.uid, err);
        this.adapter.ClientQuit(socket);
        try {socket.destroy();} catch(e){};
    });
        
    // Remove the device from gateway active device list and notify adapter for eventual cleanup
    socket.on('end', function () {
	socket.controller.Debug(4, "SockClient Quit devid=%s uid=%s", socket.device.devid, socket.device.uid);
        this.adapter.ClientQuit(socket);
    });
    
}
992023
def mock_server_receive(sock, length):
    """"""
    msg = b''
    while length:
        chunk = sock.recv(length)
        if chunk == b'':
            raise socket.error(errno.ECONNRESET, 'closed')

        length -= len(chunk)
        msg += chunk

    return msg
992853
def receive(self, sock):
    """"""
    msg = None
    data = b''
    recv_done = False
    recv_len = -1
    while not recv_done:
      buf = sock.recv(BUFSIZE)
      if buf is None or len(buf) == 0:
        raise Exception("socket closed")
      if recv_len == -1:
        recv_len = struct.unpack('>I', buf[:4])[0]
        data += buf[4:]
        recv_len -= len(data)
      else:
        data += buf
        recv_len -= len(buf)
      recv_done = (recv_len == 0)

    msg = pickle.loads(data)
    return msg
658110
def initiate_handshake(self, headers, timeout=None):
        
        io_loop = IOLoop.current()
        timeout = timeout or DEFAULT_INIT_TIMEOUT_SECS

        self.writer.put(messages.InitRequestMessage(
            version=PROTOCOL_VERSION,
            headers=headers
        ))

        init_res_future = self.reader.get()
        timeout_handle = io_loop.call_later(timeout, (
            lambda: init_res_future.set_exception(errors.TimeoutError(
                'Handshake with %s:%d timed out. Did not receive an INIT_RES '
                'after %s seconds' % (
                    self.remote_host, self.remote_host_port, str(timeout)
                )
            ))
        ))
        io_loop.add_future(
            init_res_future,
            (lambda _: io_loop.remove_timeout(timeout_handle)),
        )

        init_res = yield init_res_future
        if init_res.message_type != Types.INIT_RES:
            raise errors.UnexpectedError(
                "Expected handshake response, got %s" % repr(init_res)
            )
        self._extract_handshake_headers(init_res)
        self._handshake_performed = True

        # The receive loop is started only after the handshake has been
        # completed.
        self._loop()

        raise tornado.gen.Return(init_res)
790808
def _accept(self, listen_socket):
        
        conn, addr = listen_socket.accept()
        connection = TelnetConnection(conn, addr, self.application, self, encoding=self.encoding)
        self.connections.add(connection)

        logger.info('New connection %r %r', *addr)