@phper
2017-05-04T18:17:14.000000Z
字数 2746
阅读 4830
swoole
swoole也是支持WebSocket的。websocket也是基于单个TCP 连接上进行全双工通讯的协议,简单的说它是支持长连接。全双工通讯异味这信息的实时性。在websocket之前一直用long poll 和 ajax轮询的方式来实现实时通讯。
websocket既然是基于TCP,那么也分服务端,和客户端。
先直接来看下,swoole如何实现一个websocket服务端吧:
<?php
/**
* WebSocket
* User: yangyi
* Date: 2017/5/4
* Time: 11:54
*/
$server = new Swoole\WebSocket\Server("0.0.0.0", 9502);
$server->on('open', function (Swoole\WebSocket\Server $server, $request) {
echo "server: handshake success with fd{$request->fd}\n";
});
$server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
$server->push($frame->fd, "this is server");
});
$server->on('close', function (Swoole\WebSocket\Server $server, $fd) {
echo "client {$fd} closed\n";
});
$server->start();
启动服务。
php websocket_server.php
然后,再来实现一个简单的html js websocket 客户端:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:9502");
ws.onopen = function(){
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("send:Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("received:" + received_msg);
};
ws.onclose = function() {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>
在浏览器打开这个页面,点击,就可以看到弹框消息了。打开控制台可以看到有2条消息在实时传输:
Data | Length | Time |
---|---|---|
Message to send | 15 | 15:55:08.792 |
this is server | 14 | 15:55:10.445 |
服务端的日志也可以看到:
server: handshake success with fd14
receive from 14:Message to send,opcode:1,fin:1
当WebSocket客户端与服务器建立连接并完成握手后会回调此函数。
$server->on('open', function (Swoole\WebSocket\Server $server, $request) {
echo "server: handshake success with fd{$request->fd}\n";
});
当服务器收到来自客户端的数据帧时会回调此函数。
function onMessage(swoole_server $server, swoole_websocket_frame $frame)
$frame 共有4个属性,分别是:
$data 如果是文本类型,编码格式必然是UTF-8,这是WebSocket协议规定的
向websocket客户端连接推送数据,长度最大不得超过2M。
function swoole_websocket_server->push(int $fd, string $data, int $opcode = 1, bool $finish = true);
WEBSOCKET_OPCODE_BINARY_FRAME
发送成功返回true,发送失败返回false