Swoole UDP Server
518463
public function udp()
    {
        $this->writeln('Starting swoole udp server...');

        $udpServer = new TcpServer(
            $this->swooleConfig['upd']['host'] ?? self::DEFAULT_SWOOLE_HOST,
            $this->swooleConfig['upd']['port'] ?? self::DEFAULT_SWOOLE_PORT,
            SWOOLE_PROCESS,
            SWOOLE_SOCK_UDP
        );

        //防止粘包
        $udpServer->set(
            [
            'open_eof_split' => true,
            'package_eof' => self::EOF,
            ]
        );

        $udpServer->on(
            'Packet', function ($serv, $data, $clientInfo) {
                $clientAddress = $clientInfo['address'];
                $clientPort = $clientInfo['port'];
                $jsonData = JsonHelper::decode(str_replace(self::EOF, '', $data));
                if (isset($jsonData['handler'])) {
                    $jsonData['swoole_client_info'] = $clientInfo;
                    $handlerClass = $jsonData['handler'];
                    try {
                        $serv->sendto(
                            $clientAddress,
                            $clientPort,
                            Lb::app()->dispatchJob($handlerClass, $jsonData)
                        );
                    } catch (\Throwable $e) {
                        $serv->sendto(
                            $clientAddress,
                            $clientPort,
                            'Exception:' . $e->getTraceAsString()
                        );
                    }
                } else {
                    $serv->sendto(
                        $clientAddress,
                        $clientPort,
                        'Handler not exists'
                    );
                }
            }
        );

        $udpServer->start();
    }
611089
public function handle(swoole_process $swoole_process)
    {
        timer_tick(1000, function ($id) {
            static $index = 0;
            $index++;
            echo $index . PHP_EOL;
            if ($index === 10) {
                timer_clear($id);
            }
        });
    }
92679
protected function start()
    {
        $pid = $this->getMasterPid();

        if ($this->isRunning($pid)) {
            $this->output->writeln('<error>swoole http server process is already running.</error>');
            return;
        }

        $this->output->writeln('Starting swoole http server...');

        /** @var Swoole $swoole */
        $swoole = $this->app->make(Swoole::class);

        if ($this->config['auto_reload']) {
            //热更新
            /** @var \Swoole\Server $server */
            $server = $this->app->make(\think\swoole\facade\Server::class);

            $server->addProcess($this->getHotReloadProcess($server, (int) $this->config['auto_reload']));
        }

        $host = $this->config['server']['host'];
        $port = $this->config['server']['port'];

        $this->output->writeln("Swoole http server started: <http://{$host}:{$port}>");
        $this->output->writeln('You can exit with <info>`CTRL-C`</info>');

        $swoole->run();
    }
1328724
async def create_hlk_sw16_connection(port=None, host=None,
                                     disconnect_callback=None,
                                     reconnect_callback=None, loop=None,
                                     logger=None, timeout=None,
                                     reconnect_interval=None):
    """"""
    client = SW16Client(host, port=port,
                        disconnect_callback=disconnect_callback,
                        reconnect_callback=reconnect_callback,
                        loop=loop, logger=logger,
                        timeout=timeout, reconnect_interval=reconnect_interval)
    await client.setup()

    return client
1235440
def run_server(port=8000):
    
    from http.server import BaseHTTPRequestHandler, HTTPServer

    class VerboseHTMLHandler(BaseHTTPRequestHandler):
        def do_HEAD(s):
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()

        def do_GET(s):
            global html

            data = changed_file()
            if data is not None:
                html = html_from_markdown(data)
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(standalone(html).encode('utf-8'))

    class SilentHTMLHandler(VerboseHTMLHandler):
        def log_message(self, format, *args):
            return

    port = int(port)
    server_class = HTTPServer
    handler = VerboseHTMLHandler if verbose else SilentHTMLHandler
    try:
        httpd = server_class(("localhost", port), handler)
    except PermissionError:
        sys.stderr.write("Permission denied\n")
        sys.exit(1)
    if verbose:
        print("Hosting server on port %d. Ctrl-c to exit" % port)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    if verbose:
        print("\rShutting down server")
995955
function(server) {
    var app = server.app;
    var set = app.set;

    /**
     * Emit the "set" event whenever a setting is changed
     */
    app.set = function(name, value) {
      // Track the old/new value of the setting
      var oldValue = set.call(app, name);
      var result = set.apply(app, arguments);
      var newValue = set.call(app, name);

      // If it changed, then emit the "set" event
      if (oldValue !== newValue) {
        server.emit('set', name, newValue, oldValue);
      }

      return result;
    };

    /**
     * Bubble app errors up to the Swagger Server.
     */
    app.on('error', function() {
      server.emit.apply(server, ['error'].concat(_.slice(arguments)));
    });

    /**
     * Starts listening for connections, once the Swagger API is done being parsed.
     * If no port number is given, then the port number in the Swagger API will be used.
     *
     * @returns {http.Server}
     */
    app.listen = function() {
      var args = _.slice(arguments);
      var httpServer = http.createServer(app);

      // Wait until parsing is done
      server.__parser.whenParsed(function(err, api) {
        if (_.isFunction(args[0]) || !args[0]) {
          // No port number was provided, so get it from the Swagger API
          var host = api ? api.host || '' : '';
          var hostMatches = host.match(/(?:\:(\d+))$/); // ['hostname', 'port']
          if (hostMatches && hostMatches.length === 2) {
            var portNumber = parseInt(hostMatches[1]);

            if (args.length === 0) {
              // No args were specified, so just use the port number
              args = [portNumber];
            }
            else if (_.isFunction(args[0])) {
              // A callback was specified, so insert the port number before it
              args.splice(0, 0, portNumber);
            }
            else {
              // A blank port number was specified, so replace it
              args.splice(0, 1, portNumber);
            }
          }
        }

        util.debug('Starting HTTP server');
        httpServer.listen.apply(httpServer, args);
      });

      return httpServer;
    };

    /**
     * The {@link DataStore} object that's used by the mock middleware.
     * See https://github.com/BigstickCarpet/swagger-express-middleware/blob/master/docs/exports/DataStore.md
     *
     * @type {DataStore}
     */
    Object.defineProperty(app, 'dataStore', {
      configurable: true,
      enumerable: true,
      get: function() {
        return app.get('mock data store');
      },
      set: function(value) {
        app.set('mock data store', value);
      }
    });

    // Add new app settings
    app.enable('watch files');
    app.enable('mock');
    app.set('handlers path', './handlers');

    // Add Swagger middleware
    app.use(
      poweredBy,
      server.__middleware.metadata(),
      server.__middleware.CORS(),
      server.__middleware.files(),
      server.__middleware.parseRequest(),
      server.__middleware.validateRequest()
    );

    // Store the number of swagger middleware stored in the stack not defined by the user so that when the
    // user makes a live change in the ./handlers directory we will only remove the desired results
    var mwToKeepIndex = app._router.stack.length;

    server.__removeMiddleWare = function() {

      var mwToRemove = app._router.stack.length - mwToKeepIndex - mockRange;

      app._router.stack.splice(mwToKeepIndex, mwToRemove);
    };

    // Add Swagger Mock middleware
    app.use(server.__middleware.mock());

    // Patch the routing methods
    router.patch(app._router);
    var mockRange = app._router.stack.length - mwToKeepIndex;

    // Currently the way the routing works is the middlware used to patch the Express server is added first,
    // then the Swagger mocks, and then user's custom middlware as defined in the ./handlers directory. The MW defined
    // by the user needs to come between the Express patch MW and the Mock MW so this function is called to properly
    // arrange the Express router stack to the desired order.
    app._router.__sortMiddleWare = function() {
      // This function should ever only be called after an individual user MW is added to
      // the router Stack so we only need to pop() the array once and splice it in after the
      // Swagger patch middleware.
      var userMW = app._router.stack.pop();
      app._router.stack.splice(mwToKeepIndex, 0, userMW);
    };

    /**
     * Sets the "X-Powered-By" header
     */
    function poweredBy(req, res, next) {
      if (app.enabled('x-powered-by')) {
        res.setHeader('X-Powered-By', 'Swagger Server');
      }
      next();
    }
  }
1220266
protected function createSwooleServer()
    {
        $server     = $this->isWebsocket ? WebsocketServer::class : HttpServer::class;
        $config     = $this->app->config;
        $host       = $config->get('swoole.server.host');
        $port       = $config->get('swoole.server.port');
        $socketType = $config->get('swoole.server.socket_type', SWOOLE_SOCK_TCP);
        $mode       = $config->get('swoole.server.mode', SWOOLE_PROCESS);

        static::$server = new $server($host, $port, $mode, $socketType);

        $options = $config->get('swoole.server.options');

        static::$server->set($options);
    }
1231960
function run($num=1)
    {
        //初始化事件系统
        if(!($this->protocol instanceof Swoole_UDP_Server_Protocol))
        {
            return error(902);
        }
        //建立服务器端Socket
        $this->server_sock = $this->create("udp://{$this->host}:{$this->port}");
        stream_set_blocking($this->server_sock,$this->server_block);
        $this->server_socket_id = (int)$this->server_sock;
        //设置事件监听，监听到服务器端socket可读，则有连接请求
        $this->protocol->onStart();
        $this->server_loop();
    }
394915
def udp_send(udpsock, frame, address, addrlen):
        
        return lib.zsys_udp_send(udpsock, frame, address, addrlen)
1035516
protected function configureSwooleServer()
    {
        $config = $this->app->make('config');
        $options = $config->get('swoole_http.server.options');

        // only enable task worker in websocket mode and for queue driver
        if ($config->get('queue.default') !== 'swoole' && ! $this->isWebsocket) {
            unset($options['task_worker_num']);
        }

        static::$server->set($options);
    }
675221
def _netinfo_openbsd():
    '''
    
    '''
    ret = {}
    _fstat_re = re.compile(
        r'internet(6)? (?:stream tcp 0x\S+ (\S+)|dgram udp (\S+))'
        r'(?: [<>=-]+ (\S+))?$'
    )
    out = __salt__['cmd.run']('fstat')
    for line in out.splitlines():
        try:
            user, cmd, pid, _, details = line.split(None, 4)
            ipv6, tcp, udp, remote_addr = _fstat_re.match(details).groups()
        except (ValueError, AttributeError):
            # Line either doesn't have the right number of columns, or the
            # regex which looks for address information did not match. Either
            # way, ignore this line and continue on to the next one.
            continue
        if tcp:
            local_addr = tcp
            proto = 'tcp{0}'.format('' if ipv6 is None else ipv6)
        else:
            local_addr = udp
            proto = 'udp{0}'.format('' if ipv6 is None else ipv6)
        if ipv6:
            # IPv6 addresses have the address part enclosed in brackets (if the
            # address part is not a wildcard) to distinguish the address from
            # the port number. Remove them.
            local_addr = ''.join(x for x in local_addr if x not in '[]')

        # Normalize to match netstat output
        local_addr = '.'.join(local_addr.rsplit(':', 1))
        if remote_addr is None:
            remote_addr = '*.*'
        else:
            remote_addr = '.'.join(remote_addr.rsplit(':', 1))

        ret.setdefault(
            local_addr, {}).setdefault(
                remote_addr, {}).setdefault(
                    proto, {}).setdefault(
                        pid, {})['user'] = user
        ret[local_addr][remote_addr][proto][pid]['cmd'] = cmd
    return ret
844416
public static function run()
    {
        \Swoole\Runtime::enableCoroutine();
        self::$debug = new \swoole_atomic(0);
        self::$xdebug = false;
        self::$coverage = false;
        self::$leader = new \swoole_atomic(0);
        self::$xdebug_table = new \swoole_table(1);
        self::$xdebug_table->column('wid', \swoole_table::TYPE_INT, 8);
        self::$xdebug_table->column('cid', \swoole_table::TYPE_INT, 8);
        self::$xdebug_table->create();
        self::$startTime = date('Y-m-d H:i:s');
        self::$startMillisecond = getMillisecond();
        self::setProcessTitle(getServerName());
        $application = new Application();
        $input = new ArgvInput();
        $output = new ConsoleOutput();
        self::$io = new SymfonyStyle($input, $output);
        self::addDirCommand(SERVER_DIR, "Server", $application);
        self::addDirCommand(APP_DIR, "app", $application);
        $application->run($input, $output);
    }
758472
public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
        server.setStopAtShutdown(true);
        server.setHandler(new WebAppContext("web","/dwr"));
        server.start();
        server.join();
    }
282862
function createDgramServer(options = {}) {
  let isExternalSocket = false;

  if (options.socket instanceof dgram.Socket) {
    isExternalSocket = true;
  }

  const socket = isExternalSocket ? options.socket : dgram.createSocket('udp4');
  const server = new StunServer(socket);

  if (!isExternalSocket) {
    socket.on('error', error => server.emit('error', error));
    server.once('close', () => socket.close());
  }

  return server;
}
723706
private function printServerFinger()
    {
        $version       = $this->version;
        $software      = SERVER_MODE === 'swoole' ? 'Swoole Server' : 'PHP Development Server';
        $document_root = APP_PATH . '/public';

        echo <<<EOT
-----------------------------------\033[32m
      ____    __  __  ____
     /\  _`\ /\ \/\ \/\  _`\
   __\ \ \ \ \ \ \_\ \ \ \ \ \
 /'__`\ \ ,__/\ \  _  \ \ ,__/
/\  __/\ \ \   \ \ \ \ \ \ \
\ \____ \\ \_\   \ \_\ \_\ \_\
 \/____/ \/_/    \/_/\/_/\/_/ \033[43;37mv{$version}\033[0m
 \033[0m
>>> \033[35m{$software}\033[0m started ...
Listening on \033[36;4mhttp://{$this->config['host']}:{$this->config['port']}/\033[0m
Document root is \033[34m{$document_root}\033[0m
Press Ctrl-C to quit.
-----------------------------------

EOT;

        echo "\033[32m>>> Http Server is enabled\033[0m \n";
        if ( !empty($this->config['enable_websocket']) ) {
            echo "\033[32m>>> WebSocket Server is enabled\033[0m \n";
        }
        echo "-----------------------------------\n";
    }
932859
public function doWork(swoole_server $server, $fd, $data, $from_id)
    {
        switch (trim($data)) {
            case 'quit':
                $server->send($fd, 'connection closed');
                $server->close($fd);

                break;
            case 'reload':
                $this->getSwoole()->reload();

                break;
            case 'status':
            default:
                $info = $server->stats();
                $status = '';
                foreach ($info as $key => $value) {
                    $status .= '['.date('Y-m-d H:i:s').']: '.$key.': '.$value.PHP_EOL;
                }
                $server->send($fd, $status);

                break;
        }
    }
895992
public static void main(String[] args) throws Exception {
		Eventloop eventloop = Eventloop.create().withCurrentThread();

		SimpleServer server = SimpleServer.create(socket ->
				BinaryChannelSupplier.of(ChannelSupplier.ofSocket(socket))
						.parseStream(ByteBufsParser.ofCrlfTerminatedBytes())
						.peek(buf -> System.out.println("client:" + buf.getString(UTF_8)))
						.map(buf -> {
							ByteBuf serverBuf = ByteBufStrings.wrapUtf8("Server> ");
							return ByteBufPool.append(serverBuf, buf);
						})
						.map(buf -> ByteBufPool.append(buf, CRLF))
						.streamTo(ChannelConsumer.ofSocket(socket)))
				.withListenPort(PORT);

		server.listen();

		System.out.println("Server is running");
		System.out.println("You can connect from telnet with command: telnet localhost 9922 or by running TcpClientExample");

		eventloop.run();
	}