Swoole之服务器配置

使用Swoole搭建本地服务器

实现类似apache的功能,不只是输入文字,而是输出页面

$http->set(
      [
           'enable_static_handler' => true,
           'document_root' => "/root/hdtocs/demo/data",
      ]
);

//document,设置对应目录,如果找得到对应目录,则下面代码不执行

 

测试案例:

ws_client.html

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<h1>chuangxiang--测试</h1>
<script>
var wsUrl = "ws://192.168.0.103:8812";

var websocket = new WebSocket(wsUrl);

//实例对象的onopen属性
websocket.onopen = function(evt) {
    websocket.send("Hello chaungxiang");//输出到服务器端,即发送信息
    console.log("connected-swoole-success");//输出在页面
}

//实例化 onmessage
websocket.onmessage = function(evt) {
    console.log("ws-server-return-data:"+evt.data);
}

//实例化onclose
websocket.onclose = function(evt) {
    console.log("close");
}

//实例化onerror
websocket.onerror =function(evt,e) {
    console.log("error:"+evt.data);
}
</script>
</body>
</html>

新建ws.php

class Ws {
    private $HOST = "0.0.0.0";
    private $PORT = 8812;
    public $ws = null;
    public function __construct(){
        $this->ws = new swoole_websocket_server($this->HOST, $this->PORT);
        $this->ws->set(array(
            'worker_num' =>2,
            'task_worker_num' =>2,
        ));

    $this->ws->on("open", [$this, 'onOpen']);
    $this->ws->on("message", [$this, 'onMessage']);
    $this->ws->on("close", [$this, 'onClose']);
    $this->ws->start();
}

/**
 *监听ws连接事件
 *@param $ws
 *@param $request
 */
public function onOpen($ws, $request){
    var_dump($request->fd);
}


/**
 *监听ws消息事件(收到客户端消息)
 *@param $ws
 *@param $frame
 */
public function onMessage($ws, $frame){ 
    echo "ser-push-message:{$frame->data}\n";
    $ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s"));
}


/**
 *close
 *@param $ws
 *@param $fd
 */
public function onClose($ws, $fd){
    echo "clientid:{$fd}\n";
}

 

在ws_client.html中 打开后输出:  Hello chuangxiang

http_server开启的是8812端口,充当服务器作用

ws_client.html中定义ip+ws端口,新建对象打开,在此之前必须打开ws服务。默认找到监听此端口的服务,接而实例化,执行onOpen,onMessage,之后再执行html中的onOpen.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值