zoukankan      html  css  js  c++  java
  • swoole之建立 tcp server

    一、swoole的安装

    参照官网:https://wiki.swoole.com/wiki/page/6.html

    二、代码部分

    服务端:

    <?php
    
    $host = "127.0.0.1";
    $port = 9501;
    $mode = SWOOLE_PROCESS; // 多进程模式 默认
    $sock_type = SWOOLE_SOCK_TCP; // 创建tcp socket 默认
    //创建Server对象,监听 127.0.0.1:9501端口
    $serv = new swoole_server($host, $port, $mode, $sock_type);
    
    $serv->set([
        // ps aft | grep php 查看
        'worker_num' => 4, // worker进程数 cpu核数的1-4倍
        'max_request' => 10000,
    ]);
    
    //监听连接进入事件
    /**
     * $fd 客户端连接的唯一标识符
     * $reactor_id 线程id
     */
    $serv->on('connect', function ($serv, $fd, $reactor_id) {
        echo "Client: {$fd} - {$reactor_id} - Connect.
    ";
    });
    
    //监听数据接收事件
    $serv->on('receive', function ($serv, $fd, $reactor_id, $data) {
        $serv->send($fd, "Server: {$fd} - {$reactor_id} - ".$data);
    });
    
    //监听连接关闭事件
    $serv->on('close', function ($serv, $fd) {
        echo "Client: {$fd} - Close.
    ";
    });
    
    //启动服务器
    $serv->start();

    客户端:

    <?php
    // 连接 tcp server服务器
    $client = new swoole_client(SWOOLE_SOCK_TCP);
    if (!$client->connect('127.0.0.1', 9501)) {
        exit("connect failed. Error: {$client->errCode}
    ");
    }
    // php cli常量
    fwrite(STDIN, "请输入消息:");
    $msg = trim(fgets(STDOUT));
    // 发送消息get tcp server 服务器
    $client->send("{$msg}
    ");
    // 接收来自server的数据
    echo $result = $client->recv();
    $client->close();

    也可通过 命令行:

    # telnet 127.0.0.1 9501

    进行测试

     

  • 相关阅读:
    python 如何将md5转为16字节
    linux非root用户执行开机启动程序
    python 正则表达式的使用
    Go随机数的使用
    Go 的类型断言type assertion
    go get中的...
    Go语言圣经
    python入门第三十五天--事件驱动模型(补)练习理解
    MySQL_Ubuntu安装
    JAVA入门基础--数据类型
  • 原文地址:https://www.cnblogs.com/cshaptx4869/p/10813160.html
Copyright © 2011-2022 走看看