Swoole学习(五)Swoole之简单WebSocket服务器的创建

环境:Centos6.4,PHP环境:PHP7

服务端代码

<?php
//创建websocket服务器
$host = '0.0.0.0';
$port = 9501;
$ws = new swoole_websocket_server($host, $port);

//
$ws->on('open', function($ws, $request){ //$ws就是我们的服务器,$request就是客户端的信息
    var_dump($request);
    $ws->push($request->fd,"welcome \n");
});

$ws->on('message', function($ws, $request){
    echo 'Message:'. $request->data;
    $ws->push($request->fd,'get it message');
});
$ws->on('close', function($ws, $request){
    echo 'close';
});

$ws->start();

客户端代码

<!DOCTYPE html>
<html>
<head>
    <title>WebSecket</title>
</head>
<body>
<Script>
var wsServer = 'ws://192.168.9.155:9501';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
    console.log("链接成功");
};

websocket.onclose = function (evt) {
    console.log("关闭链接");
};

websocket.onmessage = function (evt) {
    console.log('Retrieved data from server: ' + evt.data);
};

websocket.onerror = function (evt, e) {
    console.log('Error occured: ' + evt.data);
};
</Script>
</body>
</html>

文件分别是index4.php、index4.html,。

出现此状态,没有报错,说明开启成功了。

# ps -ajft  //查看进程状态

开始测试

浏览器访问index4.html

 

closeobject(Swoole\Http\Request)#8 (9) {
  ["fd"]=>
  int(12)
  ["header"]=>
  array(12) {
    ["host"]=>
    string(18) "192.168.9.155:9501"
    ["connection"]=>
    string(7) "Upgrade"
    ["pragma"]=>
    string(8) "no-cache"
    ["cache-control"]=>
    string(8) "no-cache"
    ["upgrade"]=>
    string(9) "websocket"
    ["origin"]=>
    string(15) "http://myec.com"
    ["sec-websocket-version"]=>
    string(2) "13"
    ["user-agent"]=>
    string(153) "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400"
    ["accept-encoding"]=>
    string(19) "gzip, deflate, sdch"
    ["accept-language"]=>
    string(14) "zh-CN,zh;q=0.8"
    ["sec-websocket-key"]=>
    string(24) "/nsMgwOyqsM5xmgdqpEBRA=="
    ["sec-websocket-extensions"]=>
    string(42) "permessage-deflate; client_max_window_bits"
  }
  ["server"]=>
  array(11) {
    ["request_method"]=>
    string(3) "GET"
    ["request_uri"]=>
    string(1) "/"
    ["path_info"]=>
    string(1) "/"
    ["request_time"]=>
    int(1522731778)
    ["request_time_float"]=>
    float(1522731778.6278)
    ["server_port"]=>
    int(9501)
    ["remote_port"]=>
    int(56587)
    ["remote_addr"]=>
    string(11) "192.168.9.1"
    ["master_time"]=>
    int(1522731778)
    ["server_protocol"]=>
    string(8) "HTTP/1.1"
    ["server_software"]=>
    string(18) "swoole-http-server"
  }
  ["request"]=>
  NULL
  ["cookie"]=>
  NULL
  ["get"]=>
  NULL
  ["files"]=>
  NULL
  ["post"]=>
  NULL
  ["tmpfiles"]=>
  NULL
}

OK~

posted @ 2018-01-15 10:09  温柔的风  阅读(635)  评论(0编辑  收藏  举报