什么是websockt?
websocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信—— 允许服务器主动发送信息给客户端。
为什么需要websocket
缺陷:HTTP的同学只能有客户端发起
WebSocket 特点
建立在TCP协议之上 性能开销小通信高效 客户端可以与任意服务器通信 协议标识符ws wss 持久化网络通信协议
Swoole WebSocket服务
服务端示例
t.php
<?php
$server = new Swoole\WebSocket\Server("0.0.0.0", 8818);
$server->set(
[
'enable_static_handler'=>true,
'document_root'=>"/www/wwwroot/test.cc",
]
);
$server->on("open","onOpen");
function onOpen($server,$request){
print_r($request->fd.'_打开的连接');
echo PHP_EOL;
}
$server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
echo "收到连接_{$frame->fd}发送的信息:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
$server->push($frame->fd, "后台返回给前台的信息:willem-push-sucsess");
});
$server->on('close', function ($ser, $fd) {
echo "client {$fd} closed\n";
});
$server->start();
文件位置在linux的项目根目录。
前端示例
t.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>client</title>
</head>
<h1>willem-swoole-ws测试</h1>
<script>
var wsUrl = "ws://test.cc:8818";
var websocket=new WebSocket(wsUrl);
websocket.onopen=function(evt){
websocket.send("发送 hello-willem");
console.log("conected-swoole-success");
}
websocket.onmessage=function(evt){
alert(evt.data+":接收到后端发来的信息弹窗");
console.log("ws-server-return-data:"+evt.data);
}
websocket.onclose=function(evt){
console.log("close");
}
websocket.onerror=function(evt,e){
console.log("error:"+evt.data);
}
</script>
</body>
</html>
这个代码在Windows的随便一个地方存HTML即可。
应用
1 运行程序
2 预览
3 代码优化
Ws.php
<?php
class Ws{
CONST HOST = "0.0.0.0";
CONST PORT = 8812;
public $ws = null;
public function __construct(){
$this->ws = new Swoole\WebSocket\Server("0.0.0.0",8818);
$this->ws->on("open",[$this,"onOpen"]);
$this->ws->on("message",[$this,"onMessage"]);
$this->ws->on("close",[$this,"onClose"]);
$this->ws->start();
}
public function onOpen($ws,$request){
var_dump($request->fd);
}
public function onMessage($ws,$frame){
echo "收到连接_{$frame->fd}发送的信息:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
$ws->push($frame->fd, "后台返回给前台的信息:willem-push-sucsess".date("Y-m-d H:i:s"));
}
public function onClose($ws,$fd){
echo "client:{$fd}\n";
}
}
$obj=new Ws();
|