Swoole學習(五)Swoole之簡單WebSocket伺服器的建立

OldBoy~發表於2018-01-15

環境: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~

相關文章