使用workerman简单的多人聊天室
代码如下:
- <?php
- /**
- * Created by PhpStorm.
- * User: raid
- * Date: 2016/8/2
- * Time: 11:03
- */
- use Workerman\Worker;
- require_once '../Workerman/Autoloader.php';
- $global_uid = 0;
- // 当客户端连上来时分配uid,并保存连接,并通知所有客户端
- function handle_connection($connection) {
- global $text_worker, $global_uid;
- // 为这个链接分配一个uid
- $connection->uid = ++$global_uid;
- foreach ($text_worker->connections as $conn) {
- $conn->send("user[{$connection->uid}] online");
- }
- }
- // 当客户端发送消息过来时,转发给所有人
- function handle_message($connection, $data) {
- global $text_worker;
- foreach ($text_worker->connections as $conn) {
- $conn->send("user[{$connection->uid}] said: $data");
- }
- }
- // 当客户端断开时,广播给所有客户端
- function handle_close($connection) {
- global $text_worker;
- foreach ($text_worker->connections as $conn) {
- $conn->send("user[{$connection->uid}] logout");
- }
- }
- $text_worker = new Worker("websocket://0.0.0.0:2347");
- $text_worker->count = 1;
- $text_worker->onConnect = 'handle_connection';
- $text_worker->onMessage = 'handle_message';
- $text_worker->onClose = 'handle_close';
- Worker::runAll();
HTML页面展示:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Simple Chat</title>
- </head>
- <body>
- <h1>Simple Chat</h1>
- <input type="text" id="msg">
- <button type="button" id="send">send</button>
- <div id="content"></div>
- </body>
- <script type="text/javascript">
- window.onload = function () {
- var ws = new WebSocket("ws://127.0.0.1:2347");
- document.getElementById("send").onclick = function () {
- var msg = document.getElementById("msg").value;
- ws.send(msg);
- };
- ws.onopen = function () {
- console.log("连接成功");
- // ws.send('raid');
- };
- ws.onmessage = function (e) {
- document.getElementById("content").innerHTML += "<h2>" + e.data + "</h2>";
- };
- };
- </script>
- </html>