[关闭]
@phper 2017-05-04T10:17:14.000000Z 字数 2746 阅读 450

swoole深入学习 7. WebSocket

swoole


swoole也是支持WebSocket的。websocket也是基于单个TCP 连接上进行全双工通讯的协议,简单的说它是支持长连接。全双工通讯异味这信息的实时性。在websocket之前一直用long poll 和 ajax轮询的方式来实现实时通讯。

websocket既然是基于TCP,那么也分服务端,和客户端。

websocket 例子

先直接来看下,swoole如何实现一个websocket服务端吧:

  1. <?php
  2. /**
  3. * WebSocket
  4. * User: yangyi
  5. * Date: 2017/5/4
  6. * Time: 11:54
  7. */
  8. $server = new Swoole\WebSocket\Server("0.0.0.0", 9502);
  9. $server->on('open', function (Swoole\WebSocket\Server $server, $request) {
  10. echo "server: handshake success with fd{$request->fd}\n";
  11. });
  12. $server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
  13. echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
  14. $server->push($frame->fd, "this is server");
  15. });
  16. $server->on('close', function (Swoole\WebSocket\Server $server, $fd) {
  17. echo "client {$fd} closed\n";
  18. });
  19. $server->start();

启动服务。

php websocket_server.php  

然后,再来实现一个简单的html js websocket 客户端:

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <script type="text/javascript">
  5. function WebSocketTest() {
  6. if ("WebSocket" in window) {
  7. alert("WebSocket is supported by your Browser!");
  8. // Let us open a web socket
  9. var ws = new WebSocket("ws://localhost:9502");
  10. ws.onopen = function(){
  11. // Web Socket is connected, send data using send()
  12. ws.send("Message to send");
  13. alert("send:Message is sent...");
  14. };
  15. ws.onmessage = function (evt) {
  16. var received_msg = evt.data;
  17. alert("received:" + received_msg);
  18. };
  19. ws.onclose = function() {
  20. // websocket is closed.
  21. alert("Connection is closed...");
  22. };
  23. } else {
  24. // The browser doesn't support WebSocket
  25. alert("WebSocket NOT supported by your Browser!");
  26. }
  27. }
  28. </script>
  29. </head>
  30. <body>
  31. <div id="sse">
  32. <a href="javascript:WebSocketTest()">Run WebSocket</a>
  33. </div>
  34. </body>
  35. </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的几个回调函数

onOpen

当WebSocket客户端与服务器建立连接并完成握手后会回调此函数。

  1. $server->on('open', function (Swoole\WebSocket\Server $server, $request) {
  2. echo "server: handshake success with fd{$request->fd}\n";
  3. });

onMessage

当服务器收到来自客户端的数据帧时会回调此函数。

  1. function onMessage(swoole_server $server, swoole_websocket_frame $frame)

$frame 共有4个属性,分别是:

$data 如果是文本类型,编码格式必然是UTF-8,这是WebSocket协议规定的

向客户端发送信息 push

向websocket客户端连接推送数据,长度最大不得超过2M。

function swoole_websocket_server->push(int $fd, string $data, int $opcode = 1, bool $finish = true);

发送成功返回true,发送失败返回false

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注