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,。

Swoole学习(五)Swoole之简单WebSocket服务器的创建详解程序员

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

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

Swoole学习(五)Swoole之简单WebSocket服务器的创建详解程序员

开始测试

浏览器访问index4.html

Swoole学习(五)Swoole之简单WebSocket服务器的创建详解程序员

 

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~

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/2329.html

(0)
上一篇 2021年7月16日
下一篇 2021年7月16日

相关推荐

发表回复

登录后才能评论