要实现即时通讯的 PHP 服务端,你可以采用以下步骤:
composer require cboden/ratchet
<?php
require 'vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
</head>
<body>
<input type="text" id="message" placeholder="Type your message here">
<button id="send">Send</button>
<ul id="chat"></ul>
<script>
const socket = new WebSocket('ws://localhost:8080');
const messageInput = document.getElementById('message');
const sendButton = document.getElementById('send');
const chatList = document.getElementById('chat');
socket.onmessage = function(event) {
const li = document.createElement('li');
li.textContent = event.data;
chatList.appendChild(li);
};
sendButton.addEventListener('click', function() {
socket.send(messageInput.value);
messageInput.value = '';
});
</script>
</body>
</html>
php server.php
为了实现更高级的功能,如用户认证、消息持久化等,你可以考虑使用腾讯云的即时通讯 IM 服务(https://cloud.tencent.com/product/im),它提供了丰富的功能和优化的性能。