use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this-clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this-clients-attach($conn);
echo New connection! ({$conn-resourceId})\n;
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this-clients as $client) {
if ($from !== $client) {
$client-send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this-clients-detach($conn);
echo Connection {$conn-resourceId} has disconnected\n;
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo An error has occurred: {$e-getMessage()}\n;
$conn-close();
}
}
$server = IoServer::factory(
new HttpServer(new WsServer(new Chat())),
8080
);
echo Chat server started on port 8080\n;
$server-run();
function sendMessage() {
const input = document.getElementById('message-input');
const message = input.value;
if (message.trim() === '') return;
socket.send(message);
input.value = '';
}
5、数据库设计
创建一个简单的消息表:
sql
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);