Example #1
0
 public function __construct()
 {
     define('APPLICATION_PATH', dirname(dirname(__DIR__)) . "/application");
     $this->application = new Yaf_Application(dirname(APPLICATION_PATH) . "/conf/application.ini");
     $this->application->bootstrap();
     $server = new swoole_websocket_server("0.0.0.0", 9503);
     $server->set(array('daemonize' => true));
     $server->on('Open', array($this, 'onOpen'));
     $server->on('Message', array($this, 'onMessage'));
     $server->on('Close', array($this, 'onClose'));
     $server->start();
 }
Example #2
0
 public function __construct()
 {
     //启动应用
     $this->initializationOfApp();
     // 创建swoole_http_server对象
     $server = new swoole_websocket_server("0.0.0.0", 9507);
     //$server->setGlobal(WEBSOCKET_OPCODE_TEXT);
     $server->on('open', array($this, 'onOpen'));
     $server->on('message', array($this, 'onMessage'));
     $server->on('close', array($this, 'onClose'));
     //$server->on('shutdown', array($this, 'onShutdown'));
     $server->start();
 }
Example #3
0
 public function __construct()
 {
     $serv = new swoole_websocket_server("127.0.0.1", 9503);
     $serv->set(array('daemonize' => true));
     $serv->on('Open', function ($server, $req) {
         echo "connection open: " . $req->fd;
     });
     $serv->on('Message', function ($server, $frame) {
         $server->push($frame->fd, json_encode($frame->data));
     });
     $serv->on('Close', function ($server, $fd) {
         echo "connection close: " . $fd;
     });
     $serv->start();
 }
 public function __construct()
 {
     $this->table = new swoole_table(1024);
     $this->table->column('id', swoole_table::TYPE_INT, 8);
     //1,2,4,8
     $this->table->create();
     $config_obj = Yaf_Registry::get("config");
     $live_config = $config_obj->live->toArray();
     $server = new swoole_websocket_server($live_config['ServerIp'], $live_config['port']);
     if (isset($live_config['logfile'])) {
         $server->set(array('daemonize' => true, 'log_file' => $live_config['logfile']));
     } else {
         $server->set(array('daemonize' => true));
     }
     $server->on('Open', array($this, 'onOpen'));
     $server->on('Message', array($this, 'onMessage'));
     $server->on('Close', array($this, 'onClose'));
     $server->start();
 }
Example #5
0
 public function __construct()
 {
     define('APPLICATION_PATH', dirname(dirname(__DIR__)) . "/application");
     define('MYPATH', dirname(APPLICATION_PATH));
     $this->application = new Yaf_Application(dirname(APPLICATION_PATH) . "/conf/application.ini");
     $this->application->bootstrap();
     $config_obj = Yaf_Registry::get("config");
     $live_config = $config_obj->live->toArray();
     $server = new swoole_websocket_server($live_config['ServerIp'], $live_config['port']);
     //ssl配置,注意编译swoole的时候需要加上--enable-openssl选项
     //$server = new swoole_websocket_server($live_config['ServerIp'], $live_config['port'], SWOOLE_BASE, SWOOLE_SOCK_TCP | SWOOLE_SSL);
     if (isset($live_config['logfile'])) {
         $server->set(array('daemonize' => true, 'log_file' => $live_config['logfile']));
     } else {
         $server->set(array('daemonize' => true));
     }
     $server->on('Open', array($this, 'onOpen'));
     $server->on('Message', array($this, 'onMessage'));
     $server->on('Close', array($this, 'onClose'));
     $server->start();
 }
 public function bind($host, $port, $options = array())
 {
     $this->server = new \swoole_websocket_server($host, $port);
     $this->server->set(array('task_worker_num' => 8, 'daemonize' => $options['daemon'], 'log_file' => $options['log-file']));
     $this->server->on('Close', array($this, 'onClose'));
     $this->server->on('Message', function ($server, $frame) {
         $this->process($frame->data, $frame->fd);
     });
     $this->server->on('Task', array($this, 'onTask'));
     $this->server->on('Finish', function ($server, $task_id, $data) {
         Cli::out("Task #{$task_id} finished.");
     });
     if (!empty($options['tcp-host'])) {
         $this->server->addlistener($options['tcp-host'], $options['tcp-port'], SWOOLE_SOCK_TCP)->set(array('open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4, 'package_max_length' => 102400));
         $this->server->on('Receive', function ($server, $fd, $from, $data) {
             $this->process(substr($data, 4), $fd);
         });
         Cli::out("Additionally listening on " . sprintf("tcp://%s:%d", $options['tcp-host'], $options['tcp-port']));
     }
     return $this;
 }
Example #7
0
<?php

$server = new swoole_websocket_server("0.0.0.0", 8080);
$server->on('message', function (swoole_websocket_server $server, $frame) {
    foreach ($server->connection_list() as $fd) {
        $server->push($fd, $frame->data, true);
    }
});
$server->start();
Example #8
0
<?php

/**
 * Created by guoyu.
 * User: zhangguoyu
 * Date: 9/26/15
 * Time: 6:25 PM
 */
$serv = new swoole_websocket_server("0.0.0.0", 9527, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);
$serv->set(array("reactor_num" => 4, "worker_num" => 4, "max_request" => 50, "daemonize" => 1, "log_file" => "/tmp/swoole.log", "ssl_cert_file" => "/etc/nginx/dev.crt", "ssl_key_file" => "/etc/nginx/bz-inc.com.key", 'heartbeat_idle_time' => 600, 'heartbeat_check_interval' => 30));
$serv->on('Start', function (swoole_websocket_server $server) {
    swoole_set_process_name('php swoole_websocket.php:master');
});
$serv->on('ManagerStart', function (swoole_websocket_server $server) {
    swoole_set_process_name('php swoole_web_socket.php:manager');
});
$serv->on('WorkerStart', function (swoole_websocket_server $server, $worker_id) {
    if ($worker_id >= $server->setting['worker_num']) {
        swoole_set_process_name('php swoole_websocket.php:task worker ' . $worker_id);
    } else {
        swoole_set_process_name('php swoole_websocket.php:event worker ' . $worker_id);
    }
});
$serv->on('Open', function (swoole_websocket_server $server, $req) {
    echo date('Ymd H:i:s') . " connection open: " . $req->fd;
    echo "\n";
    // 处理断开非法连接和发送欢迎信息
    if ($req->server["path_info"] != '/im') {
        echo 'illegal client connection close';
        $server->close($req->fd);
    } else {
Example #9
0
    }
    if (0 === preg_match('#^[+/0-9A-Za-z]{21}[AQgw]==$#', $request->header['sec-websocket-key']) || 16 !== strlen(base64_decode($request->header['sec-websocket-key']))) {
        //Header Sec-WebSocket-Key is illegal;
        $response->end();
        return false;
    }
    $key = base64_encode(sha1($request->header['sec-websocket-key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
    $headers = array('Upgrade' => 'websocket', 'Connection' => 'Upgrade', 'Sec-WebSocket-Accept' => $key, 'Sec-WebSocket-Version' => '13', 'KeepAlive' => 'off');
    foreach ($headers as $key => $val) {
        $response->header($key, $val);
    }
    $response->status(101);
    $response->end();
    return true;
}
$server->on('handshake', 'user_handshake');
$server->on('open', function (swoole_websocket_server $_server, swoole_http_request $request) {
    echo "server#{$_server->worker_pid}: handshake success with fd#{$request->fd}\n";
});
$server->on('message', function (swoole_websocket_server $_server, $frame) {
    echo "received " . strlen($frame->data) . " bytes\n";
    //echo "receive from {$fd}:{$data},opcode:{$opcode},fin:{$fin}\n";
    $data = $frame->data;
    echo $data;
    $data = json_decode($data, true);
    $msg = [];
    if ($data['action'] == 'login') {
        $fd = $frame->fd;
        $uid = $data['uid'];
        $data = $data['data'];
        $data['fd'] = $fd;
Example #10
0
<?php

/**
 * WebSocket Server.
 *
 * @see http://www.w3.org/TR/2012/CR-websockets-20120920/
 * @see https://tools.ietf.org/html/rfc6455
 */
$websocketServer = new swoole_websocket_server('127.0.0.1', 8080);
$websocketServer->on('open', function ($server, $request) {
    $data = json_encode(['time' => time(), 'message' => 'Merhaba!']);
    $server->push($request->fd, $data);
});
$websocketServer->on('message', function ($server, $frame) {
    $data = json_encode(['time' => time(), 'message' => htmlspecialchars($frame->data, ENT_NOQUOTES | ENT_HTML5, 'UTF-8')]);
    foreach ($server->connections as $client) {
        $server->push($client, $data);
    }
});
$websocketServer->start();
Example #11
0
<?php

$server = new swoole_websocket_server("", 9501);
$server->on('open', function (swoole_websocket_server $server, $request) {
    echo "server: handshake success with fd{$request->fd}\n";
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    $conn_list = $server->connection_list();
    //var_dump($conn_list); 广播
    foreach ($conn_list as $fd) {
        $server->push($fd, "from: client{$frame->fd}, content: " . $frame->data);
    }
    //$server->push($frame->fd, "from: client{$fd}, content: ".$frame->data);
});
$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});
$server->start();
Example #12
0
define('CONTENT_MAXLEN', 500);
//创建websocket服务器对象,监听127.0.0.1:9009端口
$ws = new swoole_websocket_server("127.0.0.1", 9009);
//机器人类
$robot = new Robot();
//在线用户详情记录
$table = new swoole_table(1024 * 10);
$table->column('name', swoole_table::TYPE_STRING, 16);
$table->column('fd', swoole_table::TYPE_INT);
$table->column('dateline', swoole_table::TYPE_INT);
$table->column('avatar', swoole_table::TYPE_INT);
$table->column('ip', swoole_table::TYPE_STRING, 16);
$table->create();
$ws->table_user = $table;
$ws->on('open', function ($ws, $request) {
    $ws->push($request->fd, jsonResult('open', SUCCESS_CODE, "连接成功!\n"));
});
$frames_data = array();
$ws->on('message', function ($ws, $frame) {
    global $robot, $frames_data;
    $frames_data[$frame->fd] = isset($frames_data[$frame->fd]) ? $frames_data[$frame->fd] : '';
    $frames_data[$frame->fd] .= $frame->data;
    if ($frame->finish) {
        $json = $frames_data[$frame->fd];
        $msg = json_decode($json, true);
        unset($frames_data[$frame->fd]);
        if (JSON_ERROR_NONE == json_last_error()) {
            $act = $msg['action'];
            switch ($act) {
                case 'login':
                    //用户登录
Example #13
0
$table->create();
$table->set('uptime', array('cmd' => $uptime_path));
$server = new swoole_websocket_server($host, $port);
$server->table = $table;
//将table保存在serv对象上
/**
 * websocket server配置
 */
$server->set(array('worker_num' => 1, 'daemonize' => false, 'max_request' => 1000, 'dispatch_mode' => 1));
/**
 * websocket server start
 * 成功后回调
 */
$server->on('start', function ($serv) use($_maxMasterPidLength, $_maxManagerPidLength, $_maxWorkerIdLength, $_maxWorkerPidLength) {
    echo "\n----------------------- SWOOLE -----------------------------\n";
    echo 'swoole version:' . swoole_version() . "          PHP version:" . PHP_VERSION . "\n";
    echo "------------------------ WORKERS ---------------------------\n";
    echo "MasterPid", str_pad('', $_maxMasterPidLength + 2 - strlen('MasterPid')), "ManagerPid", str_pad('', $_maxManagerPidLength + 2 - strlen('ManagerPid')), "WorkerId", str_pad('', $_maxWorkerIdLength + 2 - strlen('WorkerId')), "WorkerPid", str_pad('', $_maxWorkerPidLength + 2 - strlen('WorkerPid')), "\n";
});
/**
 * 当worker 启动的时候调用
 */
$server->on('workerStart', function ($serv, $worker_id) use($_maxMasterPidLength, $_maxManagerPidLength, $_maxWorkerIdLength, $_maxWorkerPidLength) {
    echo str_pad($serv->master_pid, $_maxMasterPidLength + 2), str_pad($serv->manager_pid, $_maxManagerPidLength + 2), str_pad($serv->worker_id, $_maxWorkerIdLength + 2), str_pad($serv->worker_pid, $_maxWorkerIdLength), "\n";
    if ($worker_id == 0) {
        $data = $serv->table->get('uptime');
        $serv->tick(1000, function ($id) use($serv, $data) {
            $conn_list = $serv->connection_list();
            if (!empty($conn_list)) {
                $str = exec($data['cmd'], $string);
                foreach ($conn_list as $fd) {
                    $conn = $serv->connection_info($fd);
Example #14
0
 public function actionSwooleserver()
 {
     $host = '0.0.0.0';
     $port = 9501;
     $server = new \swoole_websocket_server($host, $port);
     $server->on('open', function (\swoole_websocket_server $server, $request) {
         echo "server: handshake success with fd{$request->fd} \n";
     });
     $server->on('message', function (\swoole_websocket_server $server, $frame) {
         echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
         $key = $frame->data;
         $reply = 'this is swoole server: your key=' . $key;
         //Yii::log('serializer='.Yii::$app->cache->serializer);// yii 对memcache的value序列化存储了
         $listOri = Yii::$app->cache->get($key);
         //$this->keyAdd;
         $list = @json_decode($listOri, true);
         //print_r($list);
         $data = ['code' => 0, 'msg' => 'ok', 'data' => ['reply' => $reply, 'total' => count($list), 'list' => $list]];
         $server->push($frame->fd, json_encode($data));
     });
     $server->on('close', function ($ser, $fd) {
         echo "client {$fd} closed\n";
     });
     $server->start();
     echo "swolle server start by {$host}:{$port}\n";
 }
Example #15
0
<?php

//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
    var_dump($request->fd, $request->get, $request->server);
    $start_fd = 0;
    while (true) {
        $conn_list = $ws->connection_list($start_fd, 10);
        if ($conn_list === false or count($conn_list) === 0) {
            echo "finish\n";
            break;
        }
        $start_fd = end($conn_list);
        var_dump($conn_list);
        foreach ($conn_list as $fd) {
            $ws->push($fd, "消息: " . $request->fd . "来到了房间");
        }
    }
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
    echo "Message: {$frame->data}\n";
    $start_fd = 0;
    while (true) {
        $conn_list = $ws->connection_list($start_fd, 10);
        if ($conn_list === false or count($conn_list) === 0) {
            echo "finish\n";
            break;
        }
Example #16
0
    foreach ($user_id_list as $uid) {
        $user_list[$uid] = $redis->get('uid_' . $uid);
    }
    return $user_list;
}
function flush_data(&$redis)
{
    $redis->delete('uid_list');
    echo 'flusth_data';
}
try {
    $serv = new swoole_websocket_server("127.0.0.1", 9503);
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    $serv->on('Open', function ($server, $req) {
        echo "connection open: " . $req->fd . "\n";
    });
    $serv->on('Message', function ($server, $frame) use($redis, $serv) {
        $request = json_decode($frame->data, true);
        print_r($request);
        $cmd = $request['cmd'];
        $data = $request['data'];
        switch ($cmd) {
            case 'login':
                $uid = 'uid_' . $frame->fd;
                $redis->lpush('uid_list', $frame->fd);
                $username = $data['username'];
                $redis->set($uid, $username);
                $user_list = get_online_users($redis);
                $response = ['cmd' => 'login', 'data' => ['user' => $username, 'user_list' => $user_list]];
                $response_data = json_encode($response);
Example #17
0
 * websocket server配置
 */
$server->set(array('worker_num' => 1, 'daemonize' => false, 'max_request' => 1000, 'dispatch_mode' => 1));
/**
 * websocket server start
 * 成功后回调
 */
$server->on('start', function ($serv) use($_maxMasterPidLength, $_maxManagerPidLength, $_maxWorkerIdLength, $_maxWorkerPidLength) {
    echo "\n----------------------- SWOOLE -----------------------------\n";
    echo 'swoole version:' . swoole_version() . "          PHP version:" . PHP_VERSION . "\n";
    echo "------------------------ WORKERS ---------------------------\n";
    echo "MasterPid", str_pad('', $_maxMasterPidLength + 2 - strlen('MasterPid')), "ManagerPid", str_pad('', $_maxManagerPidLength + 2 - strlen('ManagerPid')), "WorkerId", str_pad('', $_maxWorkerIdLength + 2 - strlen('WorkerId')), "WorkerPid", str_pad('', $_maxWorkerPidLength + 2 - strlen('WorkerPid')), "\n";
    global $process;
    //将process->pipe加入到swoole的reactor事件监听中
    swoole_event_add($process->pipe, function ($pipe) use($process, $serv) {
        $str = $process->read();
        $conn_list = $serv->connection_list();
        if (!empty($conn_list)) {
            foreach ($conn_list as $fd) {
                $serv->push($fd, $str);
            }
        }
    });
});
/**
 * swoole_process回调函数
 * @param swoole_process $worker
 */
function callback_vmstat(swoole_process $worker)
{
    global $table;
Example #18
0
<?php

$ssl_dir = realpath('../../tests/ssl');
$serv = new swoole_websocket_server("0.0.0.0", 9502, SWOOLE_BASE, SWOOLE_SOCK_TCP | SWOOLE_SSL);
//$serv = new swoole_websocket_server("0.0.0.0", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);
$serv->set(['ssl_cert_file' => $ssl_dir . '/ssl.crt', 'ssl_key_file' => $ssl_dir . '/ssl.key', 'worker_num' => 1]);
$port = $serv->listen('127.0.0.1', 9501, SWOOLE_SOCK_TCP);
$port->on('receive', function ($serv, $fd, $reactor_id, $data) {
    var_dump($fd, $reactor_id, $data);
    $serv->send($fd, "Swoole: {$data}");
});
$serv->on('connect', function ($_server, $fd) {
    echo "client {$fd} connect\n";
});
$serv->on('open', function (swoole_websocket_server $_server, swoole_http_request $request) {
    echo "server#{$_server->worker_pid}: handshake success with fd#{$request->fd}\n";
    //    var_dump($request);
});
$serv->on('request', function ($req, $resp) {
    $resp->end(file_get_contents(__DIR__ . '/websocket_client.html'));
});
$serv->on('message', function (swoole_websocket_server $_server, $frame) {
    var_dump($frame->data);
    echo "received " . strlen($frame->data) . " bytes\n";
    $_send = str_repeat('B', rand(100, 800));
    $_server->push($frame->fd, $_send);
    // echo "#$i\tserver sent " . strlen($_send) . " byte \n";
});
$serv->on('close', function ($_server, $fd) {
    echo "client {$fd} closed\n";
});
<?php

/**
 * ws_server.php
 *
 * @User    : wsj6563@gmail.com
 * @Date    : 16/1/29 14:38
 * @Encoding: UTF-8
 * @Created by PhpStorm.
 */
$ws = new swoole_websocket_server('0.0.0.0', 9502);
$ws->on('open', function (swoole_websocket_server $ws, $request) {
    var_dump($request->fd, $request->get, $request->server);
    $ws->push($request->fd, "hello,welcome\n");
});
$ws->on('message', function (swoole_websocket_server $ws, $frame) {
    echo "Message:{$frame->data}\n";
    $ws->push($frame->fd, "server:{$frame->data}");
});
$ws->on('close', function (swoole_websocket_server $ws, $fd) {
    echo "Client-{$fd} is closed";
});
$ws->start();
<?php

$map = [];
$server = new swoole_websocket_server("0.0.0.0", 9501);
$server->on('open', function (swoole_websocket_server $server, $request) use(&$map) {
    var_dump($request);
    echo "server: handshake success with fd{$request->fd}\n";
    $map[$request->fd] = $request->fd;
});
$server->on('message', function (swoole_websocket_server $server, $frame) use(&$map) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    // var_dump($map);
    foreach ($map as $id => $value) {
        $server->push($id, "this is server, " . $frame->data);
    }
});
$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});
$server->start();
Example #21
0
    }
    if (0 === preg_match('#^[+/0-9A-Za-z]{21}[AQgw]==$#', $request->header['sec-websocket-key']) || 16 !== strlen(base64_decode($request->header['sec-websocket-key']))) {
        //Header Sec-WebSocket-Key is illegal;
        $response->end();
        return false;
    }
    $key = base64_encode(sha1($request->header['sec-websocket-key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
    $headers = array('Upgrade' => 'websocket', 'Connection' => 'Upgrade', 'Sec-WebSocket-Accept' => $key, 'Sec-WebSocket-Version' => '13', 'KeepAlive' => 'off');
    foreach ($headers as $key => $val) {
        $response->header($key, $val);
    }
    $response->status(101);
    $response->end();
    return true;
}
$server->on('handshake', 'user_handshake');
$server->on('open', function (swoole_websocket_server $_server, swoole_http_request $request) {
    echo "server#{$_server->worker_pid}: handshake success with fd#{$request->fd}\n";
    //    var_dump($request);
});
$server->on('message', function (swoole_websocket_server $_server, $frame) {
    var_dump($frame);
    echo "received " . strlen($frame->data) . " bytes\n";
    //echo "receive from {$fd}:{$data},opcode:{$opcode},fin:{$fin}\n";
    $_server->push($frame->fd, "this is server");
    //	$_server->close($frame->fd);
});
$server->on('close', function ($_server, $fd) {
    echo "client {$fd} closed\n";
});
$server->on('packet', function ($_server, $data, $client) {
Example #22
0
    static $users = array();
    static $files = array();
    static $watchList = array();
    static $inotify;
}
$server = new swoole_websocket_server("0.0.0.0", 9502, SWOOLE_BASE);
$server->on('WorkerStart', function (swoole_websocket_server $server, $worker_id) {
    G::$inotify = inotify_init();
    swoole_event_add(G::$inotify, function ($ifd) use($server) {
        $events = inotify_read(G::$inotify);
        if (!$events) {
            return;
        }
        foreach ($events as $event) {
            $filename = G::$watchList[$event['wd']];
            $line = fgets(G::$files[$filename]['fp']);
            if (!$line) {
                echo "fgets failed\n";
            }
            //遍历监听此文件的所有用户,进行广播
            foreach (G::$files[$filename]['users'] as $fd) {
                $server->push($fd, $line);
            }
        }
    });
});
$server->on('Message', function (swoole_websocket_server $server, $frame) {
    echo "message: " . $frame->data;
    $result = json_decode($frame->data, true);
    $filename = $result['filename'];
    //以文件名作为数组的值,Key是fd
    $filename = __DIR__ . '/' . $filename;
Example #23
0
        //Header Sec-WebSocket-Key is illegal;
        $response->end();
        return false;
    }
    $key = base64_encode(sha1($request->header['sec-websocket-key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
    $headers = array('Upgrade' => 'websocket', 'Connection' => 'Upgrade', 'Sec-WebSocket-Accept' => $key, 'Sec-WebSocket-Version' => '13', 'KeepAlive' => 'off');
    foreach ($headers as $key => $val) {
        $response->header($key, $val);
    }
    $response->status(101);
    $response->end();
    return true;
}
//$server->on('handshake', 'user_handshake');
$server->on('open', function (swoole_websocket_server $_server, swoole_http_request $request) {
    echo "server#{$_server->worker_pid}: handshake success with fd#{$request->fd}\n";
    //    var_dump($request);
});
$server->on('message', function (swoole_websocket_server $_server, $frame) {
    //var_dump($frame);
    echo "received " . strlen($frame->data) . " bytes\n";
    if ($frame->data == "close") {
        $_server->close($frame->fd);
    } elseif ($frame->data == "task") {
        $_server->task(['go' => 'die']);
    } else {
        $_send = str_repeat('B', rand(100, 800));
        $_server->push($frame->fd, $_send);
        // echo "#$i\tserver sent " . strlen($_send) . " byte \n";
    }
});
$server->on('close', function ($_server, $fd) {
Example #24
0
 public function __construct($opt, $config = 'default')
 {
     $this->webPath = $opt['path'];
     if (!empty($opt['config'])) {
         $this->configPath = $opt['config'];
     }
     $ip = empty($opt['ip']) ? '0.0.0.0' : $opt['ip'];
     $port = empty($opt['port']) ? '9501' : $opt['port'];
     $http = new swoole_websocket_server($ip, $port);
     if (isset($opt['d'])) {
         $daemonize = 1;
     } else {
         $daemonize = 0;
     }
     $worker_num = empty($opt['worker']) ? 4 : $opt['worker'];
     $http->set(array('worker_num' => $worker_num, 'daemonize' => $daemonize, 'max_request' => 0));
     $http->setGlobal(HTTP_GLOBAL_ALL, HTTP_GLOBAL_GET | HTTP_GLOBAL_POST);
     $http->on('WorkerStart', array($this, 'onWorkerStart'));
     $http->on('WorkerError', array($this, 'onWorkerError'));
     $http->on('WorkerStop', array($this, 'onWorkerStop'));
     $http->on('close', function () {
         $params = func_get_args();
         $conn = $params[0]->connection_info($params[1]);
         if ($conn['websocket_status'] > 1) {
             $parse = ZFactory::getInstance(ZConfig::getField('socket', 'parse_class', 'WebSocketChatParse'));
             $parse->close($this->zphp, $params[1]);
         }
     });
     $http->on('open', function ($response) {
         $parse = ZFactory::getInstance(ZConfig::getField('socket', 'parse_class', 'WebSocketChatParse'));
         $parse->open($this->zphp, $response->fd);
     });
     $http->on('message', function ($server, $frame) {
         HttpServer::$wsfarme = $frame;
         $parse = ZFactory::getInstance(ZConfig::getField('websocket', 'parse_class', 'WebSocketChatParse'));
         $parse->message($this->zphp, $frame);
     });
     $http->on('request', function ($request, $response) {
         HttpServer::$request = $request;
         HttpServer::$response = $response;
         $_SERVER['PATH_INFO'] = $request->server['path_info'];
         if ($_SERVER['PATH_INFO'] == '/') {
             if (!empty($this->defaultFiles)) {
                 foreach ($this->defaultFiles as $file) {
                     $staticFile = $this->getStaticFile(DIRECTORY_SEPARATOR . $file);
                     if (is_file($staticFile)) {
                         $response->end(file_get_contents($staticFile));
                         return;
                     }
                 }
             }
         }
         if ($_SERVER['PATH_INFO'] == '/favicon.ico') {
             $response->header('Content-Type', $this->mimes['ico']);
             $response->end('');
             return;
         }
         $staticFile = $this->getStaticFile($_SERVER['PATH_INFO']);
         if (\is_dir($staticFile)) {
             //是目录
             foreach ($this->defaultFiles as $file) {
                 if (is_file($staticFile . $file)) {
                     $response->header('Content-Type', 'text/html');
                     $response->end(file_get_contents($staticFile . $file));
                     return;
                 }
             }
         }
         $ext = \pathinfo($_SERVER['PATH_INFO'], PATHINFO_EXTENSION);
         if (isset($this->mimes[$ext])) {
             //非法的扩展名
             if (\is_file($staticFile)) {
                 //读取静态文件
                 $response->header('Content-Type', $this->mimes[$ext]);
                 $response->end(file_get_contents($staticFile));
                 return;
             } else {
                 $response->status(404);
                 $response->end('');
                 return;
             }
         }
         try {
             ob_start();
             $result = $this->zphp->run();
             if (null == $result) {
                 $result = ob_get_contents();
             }
             ob_end_clean();
         } catch (Exception $e) {
             $result = json_encode($e->getTrace());
         }
         $response->status(200);
         $response->end($result);
     });
     self::$http = $http;
     self::$http->start();
 }
Example #25
0
<?php

require __DIR__ . '/TestServer.php';
$server = new swoole_websocket_server("0.0.0.0", 9501);
//$server = new swoole_websocket_server("0.0.0.0", 9501, SWOOLE_BASE);
$server->on('open', function (swoole_websocket_server $_server, swoole_http_request $request) {
    echo "server#{$_server->worker_pid}: handshake success with fd#{$request->fd}\n";
    //    var_dump($request);
});
$server->on('message', function (swoole_websocket_server $_server, $frame) {
    $pkg = unserialize($frame->data);
    if ($pkg['index'] % 1000 == 0) {
        echo "#{$pkg['index']} recv package. sid={$pkg['sid']}, length=" . strlen($frame->data) . ", md5=" . md5($frame->data) . "\n";
    }
});
$server->on('close', function ($_server, $fd) {
    echo "client {$fd} closed\n";
});
$server->start();
Example #26
0
<?php

//$server = new swoole_websocket_server("0.0.0.0", 9502);
$server = new swoole_websocket_server("0.0.0.0", 9502, SWOOLE_BASE);
$server->set(['worker_num' => 4]);
//
//$server->on('open', function (swoole_websocket_server $_server, swoole_http_request $request) {
//    //echo "server#{$_server->worker_pid}: handshake success with fd#{$request->fd}\n";
//
////    var_dump($request);
//});
$server->on('message', function (swoole_websocket_server $_server, $frame) {
    //var_dump($frame);
    //echo "received ".strlen($frame->data)." bytes\n";
    //echo "receive from {$fd}:{$data},opcode:{$opcode},fin:{$fin}\n";
    $_server->push($frame->fd, "server:" . $frame->data);
    //	$_server->close($frame->fd);
});
//$server->on('close', function ($_server, $fd) {
//    echo "client {$fd} closed\n";
//});
$server->start();
Example #27
0
<?php

$serv = new swoole_websocket_server("0.0.0.0", 9502);
$serv->on('Open', function ($server, $req) {
    echo "connection open: " . $req->fd . PHP_EOL;
});
$serv->on('Message', function ($server, $frame) {
    echo "message: " . $frame->data . PHP_EOL;
    $server->push($frame->fd, json_encode(["hello", "world"]));
});
$serv->on('Close', function ($server, $fd) {
    echo "connection close: " . $fd . PHP_EOL;
});
$serv->start();
if ($config['redis']['db']) {
    $redis->select($config['redis']['db']);
}
$ws = new swoole_websocket_server("0.0.0.0", 8080);
$ws->on('open', function ($ws, $request) {
    global $redis;
    $req = $request->server;
    $uri = explode('/', $req['request_uri']);
    $cb_name = $uri[1];
    $cb_pass = $uri[2];
    $hash = md5($cb_pass . $cb_name);
    //if fd is 1, the server had been restarted
    if ($request->fd == 1) {
        hash_clear($redis);
    }
    var_dump($hash, $request->fd);
    //save $fd => $hash
    if ($redis->hGet('fd.to.hash', $request->fd) != $hash) {
        $redis->hSet('fd.to.hash', $request->fd, $hash);
    }
    //save $hash => $fd, this list be used to publish msg on the channel.
    $redis->lPush('publish_' . $hash, $request->fd);
    $all = $redis->lRange($hash, 0, -1);
    $all = array_reverse($all);
    $result = array('type' => 'all', 'data' => $all);
    $ws->push($request->fd, json_encode($result));
});
$ws->on('message', function ($ws, $frame) {
    global $redis;
    $hash = $redis->hGet('fd.to.hash', $frame->fd);
    $r = json_decode($frame->data, true);
<?php

$ws = new swoole_websocket_server("0.0.0.0", 9600);
$ws->on('open', function ($ws, $request) {
    $ws->push($request->fd, "hello, welcome\n");
});
$ws->on('message', function ($ws, $frame) {
    echo "Message: {$frame->data}\n";
    $ws->push($frame->fd, "server: {$frame->data}");
});
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});
$ws->start();
Example #30
0
<?php

/**
 * 珠海魅族科技有限公司
 * Copyright (c) 2012 - 2013 meizu.com ZhuHai Inc. (http://www.meizu.com)
 * User: 陈晓发
 * Date: 2016/1/14
 * Time: 17:11
 * Framework: Codeigniter
 * Module:
 * Class:
 */
$server = new swoole_websocket_server("0.0.0.0", 9501, SWOOLE_BASE);
$server->set(array('worker_num' => 2));
$clientList = [];
$server->on('workerstart', function (swoole_websocket_server $_server) use(&$clientList) {
});
$server->on('open', function (swoole_websocket_server $_server, swoole_http_request $request) use(&$a) {
    print_r($_server);
    print_r($request);
});
$server->on('message', function (swoole_websocket_server $_server, $frame) use(&$clientList) {
    var_dump($frame);
    $_server->send($frame->fd, $a);
});
$server->on('close', function ($_server, $fd) {
    echo "client {$fd} closed\n";
});
$server->start();