任意位置建立项目目录
如 SimpleChat/
进入目录执行 composer require workerman/workerman
然后编写一个chat.php
:
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$global_uid = 0;
// 当客户端连上来时分配uid,并保存连接,并通知所有客户端
function handle_connection($connection)
{
global $text_worker, $global_uid;
// 为这个连接分配一个uid
$connection->uid = ++$global_uid;
}
// 当客户端发送消息过来时,转发给所有人
function handle_message(TcpConnection $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");
}
}
// 创建一个文本协议的Worker监听2347接口
$text_worker = new Worker("websocket://0.0.0.0:2347");
// 只启动1个进程,这样方便客户端之间传输数据
$text_worker->count = 1;
$text_worker->onConnect = 'handle_connection';
$text_worker->onMessage = 'handle_message';
$text_worker->onClose = 'handle_close';
Worker::runAll();
前端页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Chat Room</title>
<style>
body { font-family: Arial, sans-serif; }
#chat { width: 90%; max-width: 600px; margin: 0 auto; }
#messages { border: 1px solid #ccc; height: 300px; overflow-y: scroll; padding: 10px; }
#input { display: flex; margin-top: 10px; }
#input input { flex: 1; padding: 10px; border: 1px solid #ccc; }
#input button { padding: 10px; border: 1px solid #ccc; background: #007BFF; color: white; cursor: pointer; }
</style>
</head>
<body>
<div id="chat">
<h1>Chat Room</h1>
<div id="messages"></div>
<div id="input">
<input type="text" id="messageInput" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
</div>
</div>
<script>
const ws = new WebSocket('ws://localhost:2347');
const messagesDiv = document.getElementById('messages');
const messageInput = document.getElementById('messageInput');
ws.onopen = () => {
console.log('Connected to the chat server');
};
ws.onmessage = (event) => {
const message = document.createElement('div');
message.textContent = event.data;
messagesDiv.appendChild(message);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
};
function sendMessage() {
const message = messageInput.value;
if (message) {
ws.send(message);
messageInput.value = '';
}
}
messageInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>
最后使用 php chat.php
运行
评论 (0)