我正在使用php和mysql建立一个小网站。该网站还包括一个聊天应用程序,我现在使用Ratchet和php实现了一个模块。问题是我无法将聊天消息存储在一个MySql数据库。我也是Ratchet的初学者,按照这里的教程https://www.youtube.com/watch?v=RYpSG5d5IPk实现了聊天模块。谢谢提前:)我在这里发布聊天模块的代码:
的index.html
<html>
<head>
<meta charset="utf-8">
<title>React Chat</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class = "container">
<div class = "chat" id = "chatwindow"></div>
<div class = "form">
<textarea name = "message" id = "messagebox" placeholder = "Message :"></textarea>
</div>
</div>
<script src = "js/app.js"></script>
</body>
</html>
app.js
var chat = document.getElementById("chatwindow");
var msg = document.getElementById("messagebox");
var socket = new WebSocket("ws://127.0.0.1:2000");
var open = false;
function addMessage(msg){
chat.innerHTML += "<p>" + msg + "</p>";
}
msg.addEventListener("keypress",function(evt){
if (evt.keyCode != 13)
return;
evt.preventDefault();
if (msg.value == "" || !open)
return;
socket.send(JSON.stringify({
msg: msg.value
}));
addMessage(msg.value);
msg.value = "";
});
socket.onopen = function(){
open = true;
addMessage("Connected");
};
socket.onmessage = function(evt){
var data = JSON.parse(evt.data);
addMessage(data.msg);
};
socket.onclose = function(){
open = false;
addMessage("Disconnected");
};
Chat.php
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface
{
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $conn,$msg)
{
foreach($this->clients as $client)
{
if ($client !== $conn)
{
$client->send($msg);
$co = new mysqli("localhost", "root", "adil","test");
// Check connection
if ($co->connect_error) {
die("Connection failed: " . $co->connect_error);
}
else {
$query = "insert into message('$msg')";
$co->query($query);
}
}
}
}
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn,\Exception $e)
{
echo "The following error occured " . $e->getMessage();
$conn->close();
}
}
?>
server.php
<?php
require __DIR__ . '/../vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\http\HttpServer;
use Ratchet\WebSocket\WsServer;
$server = IoServer::factory(new HttpServer(new WsServer(new Chat)),2000);
$server->run();
?>