Home>Article>PHP Framework> Use webSocket and Swoole to create a small chat room (coroutine)

Use webSocket and Swoole to create a small chat room (coroutine)

谨言慎行
谨言慎行 Original
2022-02-22 00:00:19 2514browse

Preface

I wrote a simple asynchronous chat room before, and then I thought about it, let’s also do the coroutine, so I have this article. In fact, all the functions They are all pretty much the same, with just a few differences, and they are all simple.
Blog address:Using webSocket and Swoole to create a small chat room (asynchronous)
This time there are no additional functions, just one added Heartbeat, send a ping regularly from the front end, the server does not respond, that's all.

Front-end page code:

    打工人聊天室 

聊天区域

你好打工人:昵称
本次连接FD:

JS code:

When the server information is received, there will be a receipt for the first connection, or a receipt for the message sent by the server. The status difference is distinguished by msgType. If it is a receipt message for the first connection, the FD will be saved on a page and will not be displayed in the chat message area. If a message receipt is received, it will be displayed directly in the chat message area.

Also, the things sent by the front-end and back-end communication are all of the best string nature. My front-end processing method is to first combine it into an object and then convert it into a JSON string.

Server-side code
Coroutines need to be inCo\run(function () {}).

set([ 'heartbeat_idle_time' => 600, // 表示一个连接如果600秒内未向服务器发送任何数据,此连接将被强制关闭 'heartbeat_check_interval' => 60, // 表示每60秒遍历一次 ]); $server->handle('/websocket', function ($request, $ws) { $ws->upgrade(); global $wsObjects; $objectId = getObjectId($ws); $wsObjects[$objectId] = $ws; while (true) { $frame = $ws->recv(); if ($frame === '') { unset($wsObjects[$objectId]); $ws->close(); break; } else if ($frame === false) { echo 'error : ' . swoole_last_error() . "\n"; break; } else { if ($frame->data == 'close' || get_class($frame) === Swoole\WebSocket\CloseFrame::class) { unset($wsObjects[$objectId]); $ws->close(); return; } //格式化接收到json $data = json_decode($frame->data); switch ($data->msgType){ case 'open': //链接第一次 $data = json_encode([ 'fd' => $objectId, 'msgType' => 1 //代表第一次连接,前端处理fd ]); $ws->push($data); break; case 'ping': //接收到心跳 不作回复 // echo $data->msgType; break; default : // 原基础上不动,增加一些自定义 $data->msgType = 2; //代表服务器端回复 $data->time = date('Y-m-d H-i-s'); $data = json_encode($data); foreach ($wsObjects as $obj) { $obj->push($data); } } } } }); $server->start(); });

After the code is complete, you only need to execute the following PHP file on the console.

Then the front desk directly accesses your website address, mine is local 127.0.0.1

Open a few more windows to simulate multiple users, Then send a message to test:

Hello, worker.

The code is very simple and not very difficult, but it can reflect the power of webScoket and Swoole very concisely.

The above is the detailed content of Use webSocket and Swoole to create a small chat room (coroutine). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn