swoole+redis(websocket聊天室demo)
websocket是不同于http的另外⼀种⽹络通信协议,能够进⾏双向通信,基于此,可开发出各种实时通信产品,我简单做了个聊天室demo,顺便分享⼀下。
PHP的swoole扩展,正如作者所说,是PHP的异步、并⾏、⾼性能⽹络通信引擎,使⽤纯C语⾔编写,提供了,,,,,,,,,。Swoole内置了/、。
本demo⽤swoole来做server端,client端使⽤html5 websocket api,使⽤redis set数据结构存储连接标识。具体代码如下:
1,websocket.php:
<?php
/**
* Created by PhpStorm.
* User: purelightme
* Date: 2017/7/30
* Time: 15:24
*/
$ws_server = new swoole_websocket_server('0.0.0.0', 9502);
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
//$redis->flushAll();exit;
$ws_server->on('open', function ($ws, $request) use ($redis) {
$redis->sAdd('fd', $request->fd);
});
$ws_server->on('message', function ($ws, $frame) use ($redis) {
global$redis;
$fds = $redis->sMembers('fd');
foreach ($fds as$fd){
$ws->push($fd,$frame->fd.'--'.$frame->data);
//发送⼆进制数据:
$ws->push($fd,file_get_contents('imgsrc.baidu/imgad/pic/item/267f9e2f07082838b5168c32b299a9014c08f1f9.jpg'),WEBSOCKET_OPCODE_BINARY); }
});
//监听WebSocket连接关闭事件
$ws_server->on('close', function ($ws, $fd) use ($redis) {
$redis->sRem('fd',$fd);
});
$ws_server->start();
2,websocket.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
swoole扩展<script type="text/javascript">
if(window.WebSocket){
var webSocket = new WebSocket("ws://0.0.0.0:9502");
//webSocket.send("Hello,WebSocket!");
};
var content = ElementById('content');
if(event.data instanceof Blob) {
var img = ateElement("img");
img.src = ateObjectURL(event.data);
content.appendChild(img);
}else {
content.innerHTML = at('<p >⽤户id-'+event.data+'</p>');
}
};
var sendMessage = function(){
var data = ElementById('message').value;
webSocket.send(data);
}
}else{
console.log("您的浏览器不⽀持WebSocket");
}
</script>
</head>
<body>
<div >
<div id="content" ></div>
<hr/>
<div >
<input type="text" id="message" > <button onclick="sendMessage()" >发送</button> </div>
</div>
</body>
</html>
效果⼤概如下图,感兴趣的可以⾃⼰研究研究。。。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论