Blogger Information
Blog 62
fans 7
comment 2
visits 58120
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
WebSocket即时通讯原理实战
我是郭富城
Original
1180 people have browsed it

1. 概念

我们一直使用的http协议只能由客户端发起,服务端无法直接进行推送,这就导致了如果服务端有持续的变化客户端想要获知就比较麻烦。WebSocket协议就是为了解决这个问题应运而生。

2. workerman.net

https://www.workerman.net/
下载PHP socket即时通讯框架。
https://www.workerman.net/download/workermanzip

3.测试

  1. <?php
  2. use Workerman\Worker;
  3. require_once __DIR__ . '/Workerman/Autoloader.php';
  4. // 注意:这里与上个例子不同,使用的是websocket协议
  5. $ws_worker = new Worker("websocket://0.0.0.0:2000");
  6. // 启动4个进程对外提供服务
  7. $ws_worker->count = 4;
  8. // 当收到客户端发来的数据后返回hello $data给客户端
  9. $ws_worker->onMessage = function($connection, $data)
  10. {
  11. // 向客户端发送hello $data
  12. $connection->send('hello ' . $data);
  13. };
  14. // 运行worker
  15. Worker::runAll();

命令执行php ws_test.php start

打开chrome浏览器,按F12打开调试控制台,在Console一栏输入(或者把下面代码放入到html页面用js运行)

  1. // 假设服务端ip为127.0.0.1
  2. ws = new WebSocket("ws://127.0.0.1:2000");
  3. ws.onopen = function() {
  4. alert("连接成功");
  5. ws.send('tom');
  6. alert("给服务端发送一个字符串:tom");
  7. };
  8. ws.onmessage = function(e) {
  9. alert("收到服务端的消息:" + e.data);
  10. };

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post