swoole简单的聊天室demo(修正版)
2017-03-31 00:00
323 查看
搜了一下,以前的很多类型文章,都是可能采集的,基本一样,错误都一样,所以自己写了个,发来共享一下。
咱们可是抄袭文档还有互联网的,请确保你的服务器已经安装swoole1.7.7+版本扩展,9502端口未占用而且可以开启
swoole文档:https://wiki.swoole.com/wiki/...
效果:
swoole.html页面
<!DOCTYPE html> <html> <head> <title>swoole chat room</title> <meta charset="UTF-8"> <script type="text/javascript"> if(window.WebSocket){ var webSocket = new WebSocket("ws://101.200.223.48:9502"); webSocket.onopen = function (event) { //webSocket.send("Hello,WebSocket!"); }; webSocket.onmessage = function (event) { var content = document.getElementById('content'); content.innerHTML = content.innerHTML.concat('<p style="margin-left:20px;height:20px;line-height:20px;">'+event.data+'</p>'); } var sendMessage = function(){ var data = document.getElementById('message').value; webSocket.send(data); } }else{ console.log("您的浏览器不支持WebSocket"); } </script> </head> <body> <div style="width:600px;margin:0 auto;border:1px solid #ccc;"> <div id="content" style="overflow-y:auto;height:300px;"></div> <hr/> <div style="height:40px"> <input type="text" id="message" style="margin-left:10px;height:25px;width:450px;"> <button onclick="sendMessage()" style="height:28px;width:75px;">发送</button> </div> </div> </body> </html>
swoole.php代码:
<?php $ws = new swoole_websocket_server("0.0.0.0", 9502); // 设置配置 $ws->set( array( 'daemonize' => false, // 是否是守护进程 'max_request' => 10000, // 最大连接数量 'dispatch_mode' => 2, 'debug_mode'=> 1, // 心跳检测的设置,自动踢掉掉线的fd 'heartbeat_check_interval' => 5, 'heartbeat_idle_time' => 600, ) ); //监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) { $ws->push($request->fd, "hello, welcome to chatroom\n"); }); //监听WebSocket消息事件,其他:swoole提供了bind方法,支持uid和fd绑定 $ws->on('message', function ($ws, $frame) { $msg = 'from'.$frame->fd.":{$frame->data}\n"; // 分批次发送 $start_fd = 0; while(true) { // connection_list函数获取现在连接中的fd $conn_list = $ws->connection_list($start_fd, 100); // 获取从fd之后一百个进行发送 var_dump($conn_list); echo count($conn_list); if($conn_list === false || count($conn_list) === 0) { echo "finish\n"; return; } $start_fd = end($conn_list); foreach($conn_list as $fd) { $ws->push($fd, $msg); } } }); //监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd) { echo "client-{$fd} is closed\n"; $ws->close($fd); // 销毁fd链接信息 }); $ws->start();
然后直接php swoole.php启动swoole就行,多个浏览器访问swoole.html页面,可以模拟聊天室,查看推送。
相关文章推荐
- 简单的聊天室代码php+swoole
- swoole简单demo测试
- websocket聊天室,简单版本,基于swoole
- swoole和websocket简单聊天室开发
- tornado websocket 学习demo:简单聊天室
- php+as3简单聊天室(总结一下前面仙剑demo都写了些什么)
- PHP + Swoole 简单聊天室
- 用PHP+swoole做简单的聊天室
- Android天气预报 简单Demo
- Mybatis 3.2.7 简单入门Demo
- java多线程简单demo
- demo : 简单的 xslt 递归解析 xml 成 tree
- VS2017 UWP项目中使用SQLite数据库简易教程【附简单demo】
- 简单的基于socket通讯的聊天室,详细讲解
- 手动实现单向链表跟双向链表的一个简单demo
- python基于twisted框架编写简单聊天室
- 用socket实现简单聊天室
- 简单实现linux聊天室程序
- Linux socket编程(三) 简单的多线程聊天室
- netty实现简单聊天室