search
HomePHP FrameworkSwooleUse webSocket and Swoole to create a small chat room (coroutine)

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:

<!DOCTYPE html>
<html lang="en">
<head>    
<meta charset="UTF-8">    
<title>打工人聊天室</title>   
<!--需要引入jq 文件--></head><style>    
.content {        
height: 400px;        
max-width: 400px;        
overflow: auto;        
border-radius: 5px;        
border: 1px solid #f0f0f0;    
}</style>
<body>            
<div id="content" class="content">                
<p>聊天区域</p>            
</div>            
你好打工人:<samp id="nickname">昵称</samp> <br>            
本次连接FD: <samp id="fd-samp"></samp> <br>            
<input type="text" id="msg">            
<input type="hidden" id="fd" value="">            
<button id="send" onclick="send()">发送</button>
</body>
</html>

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.

<script>    
//滚动条最底部    
function scrolltest() {        
var div = document.getElementById("content");        
div.scrollTop = div.scrollHeight;    }    
var wsServer = &#39;ws://127.0.0.1:9502/websocket&#39;;    
var websocket = new WebSocket(wsServer);    
var nickname = Math.random().toString(36).substr(2);    
thisFd = &#39;&#39;;    $(&#39;#nickname&#39;).html(nickname);    
//点击发送    
function send() {        
var msg = $(&#39;#msg&#39;).val();        
var data = {            
&#39;nickname&#39;: nickname,            
&#39;fd&#39;: thisFd,            
&#39;data&#39;: msg        }        
//生成json 方便后台接收以及使用        
var data = JSON.stringify(data);        
websocket.send(data);        
//然后清空        
$(&#39;#msg&#39;).val(&#39;&#39;);    }    
//链接成功    
websocket.onopen = function (evt) {        
var data = {            
&#39;msgType&#39;: &#39;open&#39;        }        
var data = JSON.stringify(data);        
$("#content >p:last-child").after(&#39;<p> 服务器已连接,开始聊天吧 </p>&#39;);        
websocket.send(data);    };    
//链接断开    
websocket.onclose = function (evt) {        
$("#content >p:last-child").after(&#39;<p> 服务器已断开,请重新连接 </p>&#39;);    };    
//收到服务器消息    
websocket.onmessage = function (evt) {        
//握手成功后,会接受到服务端返回的fd ,msgType = 1        
//字符串格式化成json        
var data = eval(&#39;(&#39; + evt.data + &#39;)&#39;);        
// console.log(evt.data);        
switch (data.msgType) {            
case 1:                
thisFd = data.fd;                
$(&#39;#fd-samp&#39;).html(thisFd);                
$(&#39;#fd&#39;).val(thisFd);                
break;            case 2:                
if (data.nickname == nickname) {                    
data.nickname = &#39;我&#39;;                }                
$("#content >p:last-child").after(&#39;<p>&#39; + data.nickname + &#39; 在 &#39; + data.time + &#39; 说:<br>&#39; + data.data + &#39;</p>&#39;);                
//接收到消息自动触底                
scrolltest();                
break;        }    };    
//服务器异常    
websocket.onerror = function (evt, e) {        
$("#content >p:last-child").after(&#39;<p> 服务器异常 </p>&#39;);    };    
//心跳,本次新增    
function heartbeat() {        var data = {            
&#39;msgType&#39;: &#39;ping&#39;,        }        
//生成json 方便后台接收以及使用        
var data = JSON.stringify(data);        
websocket.send(data);    }    
//30 秒一次    
setInterval(heartbeat, 30000);</script>

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

<?php    
//定义获取当前的id函数    
function getObjectId(\Swoole\Http\Response $response) {        
if (PHP_VERSION_ID < 70200) {            
$id = spl_object_hash($response);        
} else {            
$id = spl_object_id($response);        }        
return $id;    }    
Co\run(function () {        
$server = new Co\Http\Server(&#39;127.0.0.1&#39;, 9502, false);        
$server->set([            
&#39;heartbeat_idle_time&#39;      => 600, 
// 表示一个连接如果600秒内未向服务器发送任何数据,此连接将被强制关闭            
&#39;heartbeat_check_interval&#39; => 60,  
// 表示每60秒遍历一次        
]);        
$server->handle(&#39;/websocket&#39;, function ($request, $ws) {            
$ws->upgrade();            
global $wsObjects;            
$objectId = getObjectId($ws);            
$wsObjects[$objectId] = $ws;            
while (true) {                
$frame = $ws->recv();                
if ($frame === &#39;&#39;) {                    
unset($wsObjects[$objectId]);                    
$ws->close();                    
break;                
} else if ($frame === false) {                    
echo &#39;error : &#39; . swoole_last_error() . "\n";                    
break;                } 
else {                    
if ($frame->data == &#39;close&#39; || get_class($frame) === Swoole\WebSocket\CloseFrame::class) 
{                        
unset($wsObjects[$objectId]);                        
$ws->close();                        
return;                    
}                    
//格式化接收到json                    
$data = json_decode($frame->data);                    
switch ($data->msgType){                        
case &#39;open&#39;:                            
//链接第一次                            
$data = json_encode([                                
&#39;fd&#39; => $objectId,                                
&#39;msgType&#39; => 1  
//代表第一次连接,前端处理fd                            
]);                            
$ws->push($data);                            
break;                        
case &#39;ping&#39;:                            
//接收到心跳 不作回复
//                            
echo  $data->msgType;                            
break;                        
default :                            
// 原基础上不动,增加一些自定义                            
$data->msgType = 2; 
//代表服务器端回复                            
$data->time = date(&#39;Y-m-d H-i-s&#39;);                            
$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
How can I contribute to the Swoole open-source project?How can I contribute to the Swoole open-source project?Mar 18, 2025 pm 03:58 PM

The article outlines ways to contribute to the Swoole project, including reporting bugs, submitting features, coding, and improving documentation. It discusses required skills and steps for beginners to start contributing, and how to find pressing is

How do I extend Swoole with custom modules?How do I extend Swoole with custom modules?Mar 18, 2025 pm 03:57 PM

Article discusses extending Swoole with custom modules, detailing steps, best practices, and troubleshooting. Main focus is enhancing functionality and integration.

How do I use Swoole's asynchronous I/O features?How do I use Swoole's asynchronous I/O features?Mar 18, 2025 pm 03:56 PM

The article discusses using Swoole's asynchronous I/O features in PHP for high-performance applications. It covers installation, server setup, and optimization strategies.Word count: 159

How do I configure Swoole's process isolation?How do I configure Swoole's process isolation?Mar 18, 2025 pm 03:55 PM

Article discusses configuring Swoole's process isolation, its benefits like improved stability and security, and troubleshooting methods.Character count: 159

How does Swoole's reactor model work under the hood?How does Swoole's reactor model work under the hood?Mar 18, 2025 pm 03:54 PM

Swoole's reactor model uses an event-driven, non-blocking I/O architecture to efficiently manage high-concurrency scenarios, optimizing performance through various techniques.(159 characters)

How do I troubleshoot connection issues in Swoole?How do I troubleshoot connection issues in Swoole?Mar 18, 2025 pm 03:53 PM

Article discusses troubleshooting, causes, monitoring, and prevention of connection issues in Swoole, a PHP framework.

What tools can I use to monitor Swoole's performance?What tools can I use to monitor Swoole's performance?Mar 18, 2025 pm 03:52 PM

The article discusses tools and best practices for monitoring and optimizing Swoole's performance, and troubleshooting methods for performance issues.

How do I resolve memory leaks in Swoole applications?How do I resolve memory leaks in Swoole applications?Mar 18, 2025 pm 03:51 PM

Abstract: The article discusses resolving memory leaks in Swoole applications through identification, isolation, and fixing, emphasizing common causes like improper resource management and unmanaged coroutines. Tools like Swoole Tracker and Valgrind

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor