PHP調用Workerman5.0實現(xiàn)一對一聊天
要實現(xiàn)一對一聊天功能,使用 Workerman 5.0 作為后端,前端可以使用 WebSocket 進行通信。以下是實現(xiàn)步驟和代碼示例。
1. 安裝 Workerman
首先,確保你已經安裝了 Workerman??梢酝ㄟ^ Composer 安裝:
composer require workerman/workerman
2. 后端代碼
創(chuàng)建一個 PHP 文件(例如 chat_server.php),用于處理 WebSocket 連接和消息傳遞。
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
// 創(chuàng)建一個 WebSocket 服務器
$ws_worker = new Worker("websocket://0.0.0.0:2346");
// 保存用戶連接的數(shù)組
$users = [];
// 當有客戶端連接時
$ws_worker->onConnect = function(TcpConnection $connection) use (&$users) {
echo "New connection\n";
};
// 當有客戶端發(fā)送消息時
$ws_worker->onMessage = function(TcpConnection $connection, $data) use (&$users) {
$message = json_decode($data, true);
if (isset($message['type'])) {
switch ($message['type']) {
case 'login':
// 用戶登錄,保存連接
$users[$message['user_id']] = $connection;
$connection->user_id = $message['user_id'];
echo "User {$message['user_id']} logged in\n";
break;
case 'chat':
// 一對一聊天
if (isset($users[$message['to_user_id']])) {
$users[$message['to_user_id']]->send(json_encode([
'type' => 'chat',
'from_user_id' => $connection->user_id,
'message' => $message['message']
));
}
break;
}
}
};
// 當客戶端斷開連接時
$ws_worker->onClose = function(TcpConnection $connection) use (&$users) {
if (isset($connection->user_id)) {
unset($users[$connection->user_id]);
echo "User {$connection->user_id} disconnected\n";
}
};
// 運行 worker
Worker::runAll();
3. 前端代碼
在前端,使用 WebSocket 連接到服務器,并實現(xiàn)登錄和發(fā)送消息的功能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Chat</title>
</head>
<body>
<div>
<input type="text" id="user_id" placeholder="Your User ID">
<button onclick="login()">Login</button>
</div>
<div>
<input type="text" id="to_user_id" placeholder="To User ID">
<input type="text" id="message" placeholder="Message">
<button onclick="sendMessage()">Send</button>
</div>
<div id="chat"></div>
<script>
let ws;
let user_id;
function login() {
user_id = document.getElementById('user_id').value;
ws = new WebSocket('ws://127.0.0.1:2346');
ws.onopen = function() {
ws.send(JSON.stringify({
type: 'login',
user_id: user_id
}));
};
ws.onmessage = function(event) {
const message = JSON.parse(event.data);
if (message.type === 'chat') {
document.getElementById('chat').innerHTML += `<p>From ${message.from_user_id}: ${message.message}</p>`;
}
};
}
function sendMessage() {
const to_user_id = document.getElementById('to_user_id').value;
const message = document.getElementById('message').value;
ws.send(JSON.stringify({
type: 'chat',
to_user_id: to_user_id,
message: message
}));
}
</script>
</body>
</html>
4. 運行服務器
在終端中運行 PHP 文件啟動 WebSocket 服務器:
php chat_server.php start
5. 測試
打開兩個瀏覽器窗口,分別輸入不同的用戶 ID 并登錄。
在一個窗口中輸入目標用戶 ID 和消息,點擊發(fā)送。
另一個窗口應該會收到消息并顯示在頁面上。
總結
通過以上步驟,你可以實現(xiàn)一個簡單的一對一聊天系統(tǒng)。Workerman 作為后端處理 WebSocket 連接和消息傳遞,前端通過 WebSocket 與服務器通信,實現(xiàn)實時聊天功能。
到此這篇關于PHP調用Workerman5.0實現(xiàn)一對一聊天的文章就介紹到這了,更多相關PHP Workerman聊天內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Paypal實現(xiàn)循環(huán)扣款(訂閱)功能
本文主要介紹了Paypal實現(xiàn)循環(huán)扣款(訂閱)的思路與方法;并對如何使用Paypal的支付接口下總結,具有很好的參考價值,下面跟著小編一起來看下吧2017-03-03

