简体   繁体   English

使用PHP,websockets和MySQL聊天

[英]Chat using PHP, websockets and MySQL

I'm trying to write a chat using this https://github.com/ghedipunk/PHP-Websockets PHP class. 我正在尝试使用此https://github.com/ghedipunk/PHP-Websockets PHP类编写聊天。 Now it looks like, on beginning JS on client side connect to server, then it sends a request once a 3 seconds, and server on every request check messages in database, and send messages to client. 现在看起来,开始客户端上的JS连接到服务器,然后每3秒发送一次请求,服务器在每个请求上检查数据库中的消息,然后将消息发送给客户端。 I think it's not good, that client sends request once a 3 sec, and I wonder how to do, that server send message to client, only when there is a new message in database? 我认为这不是很好,客户端每3秒钟发送一次请求,我想知道如何做,只有在数据库中有新消息时,服务器才向客户端发送消息? This is my extended process function: 这是我扩展的流程功能:

protected function process($user, $message) {
    $databaseHandler = mysqli_connect('blahblah');  
    $decoded = json_decode($message, true);
    $chat_id = $decoded['chatid'];
    $limit = $decoded['limit'];
    $user_id = filterString($decoded['userid'], $databaseHandler);
    $SQLQuery = "SELECT chat_messages.message, users.name FROM chat_messages JOIN users ON chat_messages.user_id=users.user_id WHERE chat_messages.chat_id = '$chat_id' ORDER BY chat_messages.message_id DESC LIMIT $limit,5;";
    $SQLResult = mysqli_query($databaseHandler, $SQLQuery);
    $i = 0;
    $arr = array();
    while ($row = mysqli_fetch_assoc($SQLResult)) {
        $i++;
        $arr[$i] = $row['name'] . ': ' . $row['message'];
    }


    $this->send($user, json_encode($arr));

}

This is JS function: 这是JS函数:

function refreshchat() {

try {
    socket.send('{"token":"' + token + '","userid":'+ userid +'"chatid":' + chatid + ',"limit":' + limit + '}');

} catch (ex) {
    console.log(ex);
}
setTimeout(refreshchat, 3000);

} }

I skipped authorization stuff in php for clearance. 我跳过了php中的授权内容以进行清除。

Thank you in advance! 先感谢您!

Well you are using setTimeout JavaScript function. 好吧,您正在使用setTimeout JavaScript函数。 It only runs once. 它只运行一次。 You can use setInterval function. 您可以使用setInterval函数。 It is run repeatedly. 它会重复运行。 ( http://www.w3schools.com/jsref/met_win_setinterval.asp ) http://www.w3schools.com/jsref/met_win_setinterval.asp

It seems you want a feature that allows the server to inform the client that there is a new chat message. 看来您想要一个允许服务器通知客户端有新聊天消息的功能。 I think using timer in Javascript is a good option. 我认为在Javascript中使用计时器是一个不错的选择。 You can also check the push notification api: https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web . 您还可以检查推送通知api: https : //developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM