WorkerMan学习篇:简单多人聊天

使用workerman简单的多人聊天室

原创  2016年08月02日 13:15:03

代码如下:

[php]  view plain  copy
  1. <?php  
  2. /** 
  3.  * Created by PhpStorm. 
  4.  * User: raid 
  5.  * Date: 2016/8/2 
  6.  * Time: 11:03 
  7.  */  
  8. use Workerman\Worker;  
  9. require_once '../Workerman/Autoloader.php';  
  10.   
  11. $global_uid = 0;  
  12.   
  13. // 当客户端连上来时分配uid,并保存连接,并通知所有客户端  
  14. function handle_connection($connection) {  
  15.     global $text_worker$global_uid;  
  16.     // 为这个链接分配一个uid  
  17.     $connection->uid = ++$global_uid;  
  18.     foreach ($text_worker->connections as $conn) {  
  19.         $conn->send("user[{$connection->uid}] online");  
  20.     }  
  21. }  
  22.   
  23. // 当客户端发送消息过来时,转发给所有人  
  24. function handle_message($connection$data) {  
  25.     global $text_worker;  
  26.     foreach ($text_worker->connections as $conn) {  
  27.         $conn->send("user[{$connection->uid}] said: $data");  
  28.     }  
  29. }  
  30.   
  31. // 当客户端断开时,广播给所有客户端  
  32. function handle_close($connection) {  
  33.     global $text_worker;  
  34.     foreach ($text_worker->connections as $conn) {  
  35.         $conn->send("user[{$connection->uid}] logout");  
  36.     }  
  37. }  
  38.   
  39. $text_worker = new Worker("websocket://0.0.0.0:2347");  
  40.   
  41. $text_worker->count = 1;  
  42.   
  43. $text_worker->onConnect = 'handle_connection';  
  44. $text_worker->onMessage = 'handle_message';  
  45. $text_worker->onClose = 'handle_close';  
  46.   
  47. Worker::runAll();  

HTML页面展示:

[php]  view plain  copy
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>Simple Chat</title>  
  6. </head>  
  7. <body>  
  8. <h1>Simple Chat</h1>  
  9. <input type="text" id="msg">  
  10. <button type="button" id="send">send</button>  
  11. <div id="content"></div>  
  12. </body>  
  13.   
  14. <script type="text/javascript">  
  15.     window.onload = function () {  
  16.         var ws = new WebSocket("ws://127.0.0.1:2347");  
  17.   
  18.         document.getElementById("send").onclick = function () {  
  19.             var msg = document.getElementById("msg").value;  
  20.             ws.send(msg);  
  21.         };  
  22.   
  23.         ws.onopen = function () {  
  24.             console.log("连接成功");  
  25. //            ws.send('raid');  
  26.         };  
  27.         ws.onmessage = function (e) {  
  28.             document.getElementById("content").innerHTML += "<h2>" + e.data + "</h2>";  
  29.         };  
  30.   
  31.   
  32.     };  
  33. </script>  
  34.   
  35. </html>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值