A WebSocket session has started - create a greenlet to host
        the IRC client, and start it.
557330
def on_start(self, host, port, channel, nickname, password):
        
        self.client = WebSocketIRCClient(host, port, channel, nickname,
                                         password, self)
        self.spawn(self.client.start)
497441
function Server(config) {
  utils.verbose(config.verbose)

  this._wsStarted = false
  this._wsStopped = false

  this._wsConfig = config
  this._wsServer = new websocket.server()

  this._onRequest = config.onRequest

  this._wsServer.addListener("request", this._onRequest)
  this._wsServer.addListener("connect", onConnect)
}
933938
def on_connect(client):
    
    print "++ Opened connection to %s" % client.addrport()
    broadcast('%s joins the conversation.\n' % client.addrport() )
    CLIENT_LIST.append(client)
    client.send("Welcome to the Chat Server, %s.\n" % client.addrport() )
543465
async def create_websocket(url: str,
                           ssl: Optional[SSLContext] = None,
                           headers: Optional[list] = None,
                           subprotocols: Optional[list] = None):
    
    url = yarl.URL(url)
    args = {}
    if headers:
        args["headers"] = headers

    # automatically use ssl if it's websocket secure
    if ssl is None:
        ssl = url.scheme == "wss"
    if ssl:
        if ssl is True:
            ssl = SSLContext()
        args["ssl_context"] = ssl
        args["autostart_tls"] = True
        args["tls_standard_compatible"] = False

    addr = (url.host, int(url.port))
    ws = Websocket()
    await ws.__ainit__(
        addr=addr, path=url.path_qs, subprotocols=subprotocols, **args)
    return ws
339018
def start(self):
        ''''''
        assert self._client is None

        logger.debug('IsolationContext[%d] starting', id(self))

        # Create the queues
        request_queue = multiprocessing.Queue()
        response_queue = multiprocessing.Queue()

        # Launch the server process
        server = Server(request_queue, response_queue)  # Do not keep a reference to this object!
        server_process = multiprocessing.Process(target=server.loop)
        server_process.start()

        # Create a client to talk to the server
        self._client = Client(server_process, request_queue, response_queue)
303863
function start(callback) {

  let {arc} = readArc()
  let close = x=> !x

  // if .arc has events and we're not clobbering with ARC_LOCAL flag
  if (arc.events || arc.queues) {
    // start a little web server
    let server = http.createServer(function listener(req, res) {
      let body = ''
      req.on('data', chunk => {
        body += chunk.toString()
      })
      req.on('end', () => {
        let message = JSON.parse(body)
        if (req.url === '/queues') {
          message.arcType = 'queue'
        } else if (req.url === '/events' || req.url === '/') {
          message.arcType = 'event'
        } else {
          res.statusCode = 404
          res.end('not found')
          console.log(chalk.red.dim('event bus 404 for URL ' + req.url))
          return
        }
        console.log(chalk.grey.dim('@' + message.arcType), chalk.green.dim(JSON.stringify(JSON.parse(body), null, 2)))
        // spawn a fork of the node process
        let subprocess = fork(path.join(__dirname, '_subprocess.js'))
        subprocess.send(message)
        subprocess.on('message', function _message(msg) {
          console.log(chalk.grey.dim(msg.text))
        })
        res.statusCode = 200
        res.end('ok')
      })
    })
    // ends our little web server
    close = function _closer() {
      try {
        server.close()
      }
      catch(e) {
        console.log('swallowing server.close error in sandbox events', e)
      }
    }
    // start listening on 3334
    server.listen(3334, callback ? callback: x=>!x)
  }
  else {
    callback()
  }
  return {close}
}
902428
def open(self, callback, instance=None, processor=None):
        
        assert not self._closed

        ws_url = self._client.ws_root
        if instance:
            ws_url += '/' + instance
            if processor:
                ws_url += '/' + processor

        self._callback = callback
        self._websocket = websocket.WebSocketApp(
            ws_url,
            on_open=self._on_websocket_open,
            on_message=self._on_websocket_message,
            on_error=self._on_websocket_error,
            subprotocols=['protobuf'],
            header=[
                '{}: {}'.format(k, self._client.session.headers[k])
                for k in self._client.session.headers
            ],
        )
        self._consumer = threading.Thread(target=self._websocket.run_forever)

        # Running this as a daemon thread improves possibilities
        # for consumers of our API to control shutdown.
        # (example: can just use time.sleep on the main thread instead of blocking on the future)
        self._consumer.daemon = True

        self._consumer.start()
288474
def start(self):
        
        if not self.is_run:
            # set class attribute
            ThreadingTCPServer.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET
            ThreadingTCPServer.daemon_threads = True
            # init server
            self._service = ThreadingTCPServer((self.host, self.port), self.ModbusService, bind_and_activate=False)
            # set socket options
            self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            # TODO test no_delay with bench
            self._service.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            # bind and activate
            self._service.server_bind()
            self._service.server_activate()
            # serve request
            if self.no_block:
                self._serve_th = Thread(target=self._serve)
                self._serve_th.daemon = True
                self._serve_th.start()
            else:
                self._serve()
568707
private synchronized void start(InetSocketAddress inetSocketAddress) throws IOException {
    if (started) throw new IllegalStateException("start() already called");
    started = true;

    executor = Executors.newCachedThreadPool(Util.threadFactory("MockWebServer", false));
    this.inetSocketAddress = inetSocketAddress;

    if (serverSocketFactory == null) {
      serverSocketFactory = ServerSocketFactory.getDefault();
    }
    serverSocket = serverSocketFactory.createServerSocket();

    // Reuse if the user specified a port
    serverSocket.setReuseAddress(inetSocketAddress.getPort() != 0);
    serverSocket.bind(inetSocketAddress, 50);

    port = serverSocket.getLocalPort();
    executor.execute(new NamedRunnable("MockWebServer %s", port) {
      @Override protected void execute() {
        try {
          logger.info(MockWebServer.this + " starting to accept connections");
          acceptConnections();
        } catch (Throwable e) {
          logger.log(Level.WARNING, MockWebServer.this + " failed unexpectedly", e);
        }

        // Release all sockets and all threads, even if any close fails.
        closeQuietly(serverSocket);
        for (Iterator<Socket> s = openClientSockets.iterator(); s.hasNext(); ) {
          closeQuietly(s.next());
          s.remove();
        }
        for (Iterator<Http2Connection> s = openConnections.iterator(); s.hasNext(); ) {
          closeQuietly(s.next());
          s.remove();
        }
        dispatcher.shutdown();
        executor.shutdown();
      }

      private void acceptConnections() throws Exception {
        while (true) {
          Socket socket;
          try {
            socket = serverSocket.accept();
          } catch (SocketException e) {
            logger.info(MockWebServer.this + " done accepting connections: " + e.getMessage());
            return;
          }
          SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
          if (socketPolicy == DISCONNECT_AT_START) {
            dispatchBookkeepingRequest(0, socket);
            socket.close();
          } else {
            openClientSockets.add(socket);
            serveConnection(socket);
          }
        }
      }
    });
  }
569077
async def start_client(self,
                           sock: anyio.abc.SocketStream,
                           addr,
                           path: str,
                           headers: Optional[List] = None,
                           subprotocols: Optional[List[str]] = None):
        
        self._sock = sock
        self._connection = WSConnection(ConnectionType.CLIENT)
        if headers is None:
            headers = []
        if subprotocols is None:
            subprotocols = []
        data = self._connection.send(
            Request(
                host=addr[0],
                target=path,
                extra_headers=headers,
                subprotocols=subprotocols))
        await self._sock.send_all(data)

        assert self._scope is None
        self._scope = True
        try:
            event = await self._next_event()
            if not isinstance(event, AcceptConnection):
                raise ConnectionError("Failed to establish a connection",
                                      event)
            return event
        finally:
            self._scope = None
634374
function WebSocketRepeater (options) {
    var self = this;
    if (!options) { options = {}; }

    var port = options.port || 8080;
    var clientCount = 0;
    var idCounter = 0;

    this.clients = [];

    var wss;

    if (options.server) {
        wss = new WebSocketServer({server: options.server});
    } else {
        wss = new WebSocketServer({port: port});
    }

    // websocket connections
    wss.on('connection', function(ws) {
        var clientInfo = {
            ws: ws,
            cid: ++idCounter,
            errored: false
        };
        self.clients.push(clientInfo);
        clientCount++;

        ws.on('message', function(message) {
            self.emit('message', message, ws);

            var messageJSON;
            var responce;

            self.clients.forEach(function (client) {
                if (client.cid !== clientInfo.cid) {
                    client.ws.send(message);
                }
            });

            // try {
            //     messageJSON = JSON.parse(message);
            // } catch (e) {}

            // if (messageJSON) {
            //     testAllRoutes(routes, ws, messageJSON);
            // } 
        });

        ws.on('close', function() {
            self.clients = _.without(self.clients, clientInfo);
            --clientCount;
            logClientCount();
        });

        ws.on('error', function () {
            logClientCount();
            clientInfo.errored = true;
        });

        logClientCount();
    });

    // start the heat beat
    if (options.useHeartbeat) {
        this.heartbeat();
    }

    function logClientCount() {
        console.log("Client count ", clientCount);
    }

}
811764
def _start_server(bindaddr, port, hostname, folder):
    """"""
    import asyncio
    from .httpserver import HttpProtocol
    loop = asyncio.get_event_loop()
    coroutine = loop.create_server(lambda: HttpProtocol(hostname, folder),
                                   bindaddr,
                                   port)
    server = loop.run_until_complete(coroutine)

    print('Starting server on {}'.format(server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
136130
public void start() throws IOException {
        myServerSocket = new ServerSocket();
        myServerSocket.bind((hostname != null) ? new InetSocketAddress(
                hostname, myPort) : new InetSocketAddress(myPort));

        myThread = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        final Socket finalAccept = myServerSocket.accept();
                        registerConnection(finalAccept);
                        finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                        final InputStream inputStream = finalAccept
                                .getInputStream();
                        asyncRunner.exec(new Runnable() {
                            @Override
                            public void run() {
                                OutputStream outputStream = null;
                                try {
                                    outputStream = finalAccept
                                            .getOutputStream();
                                    TempFileManager tempFileManager = tempFileManagerFactory
                                            .create();
                                    HTTPSession session = new HTTPSession(
                                            tempFileManager, inputStream,
                                            outputStream, finalAccept
                                                    .getInetAddress());
                                    while (!finalAccept.isClosed()) {
                                        session.execute();
                                    }
                                } catch (Exception e) {
                                    // When the socket is closed by the client,
                                    // we throw our own SocketException
                                    // to break the "keep alive" loop above.
                                    if (!(e instanceof SocketException && "NanoHttpd Shutdown"
                                            .equals(e.getMessage()))) {
                                        e.printStackTrace();
                                    }
                                } finally {
                                    safeClose(outputStream);
                                    safeClose(inputStream);
                                    safeClose(finalAccept);
                                    unRegisterConnection(finalAccept);
                                }
                            }
                        });
                    } catch (IOException e) {
                    }
                } while (!myServerSocket.isClosed());
            }
        });
        myThread.setDaemon(true);
        myThread.setName("NanoHttpd Main Listener");
        myThread.start();
    }
1233622
def client_start(request, socket, context):
    
    CLIENTS[socket.session.session_id] = (request, socket, context)
565110
def start(self):
        
        self.log.info("Starting SSL Session for Monitor %s."
                      % self.monitor_id)
        if self.socket is not None:
            raise Exception("Socket already established for %s." % self)

        try:
            # Create socket, wrap in SSL and connect.
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            # Validate that certificate server uses matches what we expect.
            if self.ca_certs is not None:
                self.socket = ssl.wrap_socket(self.socket,
                                              cert_reqs=ssl.CERT_REQUIRED,
                                              ca_certs=self.ca_certs)
            else:
                self.socket = ssl.wrap_socket(self.socket)

            self.socket.connect((self.client.hostname, PUSH_SECURE_PORT))
            self.socket.setblocking(0)
        except Exception as exception:
            self.socket.close()
            self.socket = None
            raise exception

        self.send_connection_request()
756366
def start(self):
        

        # protocol handlers
        for c in handlerbase.HandlerBase.__subclasses__():

            cap_name = c.__name__.lower()

            if cap_name in self.config['capabilities']:
                port = self.config['capabilities'][cap_name]['port']
                # carve out the options for this specific service
                options = self.config['capabilities'][cap_name]
                # capabilities are only allowed to append to the session list
                cap = c(options, self.work_dir)

                try:
                    # Convention: All capability names which end in 's' will be wrapped in ssl.
                    if cap_name.endswith('s'):
                        server = StreamServer(('0.0.0.0', port), cap.handle_session,
                                              keyfile=self.key, certfile=self.cert)
                    else:
                        server = StreamServer(('0.0.0.0', port), cap.handle_session)

                    logger.debug('Adding {0} capability with options: {1}'.format(cap_name, options))
                    self._servers.append(server)
                    server_greenlet = Greenlet(server.start())
                    self._server_greenlets.append(server_greenlet)

                except _socket.error as ex:
                    logger.error("Could not start {0} server on port {1}. Error: {2}".format(c.__name__, port, ex))
                else:
                    logger.info('Started {0} capability listening on port {1}'.format(c.__name__, port))

        stop_if_not_write_workdir(self.work_dir)
        logger.info("Honeypot running.")

        gevent.joinall(self._server_greenlets)
611257
async def open_websocket_client(sock: anyio.abc.SocketStream,
                                addr,
                                path: str,
                                headers: Optional[list] = None,
                                subprotocols: Optional[list] = None):
    """"""
    ws = await create_websocket_client(
        sock, addr=addr, path=path, headers=headers, subprotocols=subprotocols)
    try:
        yield ws
    finally:
        await ws.close()