Websockets PHP/AJAX/Javascript刷新客户端 [英] Websockets PHP / AJAX / Javascript refresh client

查看:55
本文介绍了Websockets PHP/AJAX/Javascript刷新客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Websockets与PHP和一些Javascript一起使用.我从数据库向客户端显示一些信息.我的目标是在信息插入到数据库中时刷新客户端.要在数据库中插入一些数据,请从PC发送发帖请求.

I'm using websockets with PHP and some Javascript. I display some information from my database to my client. My goal is to refresh the client when an information has insert into my database. To insert some data in my database, I send a post request from my PC.

目前,我可以每10秒刷新一次客户端以调用一个函数.但是,我只想在该页面上发送POST请求时刷新.

At the moment, I can refresh the client to call a function every 10 seconds. But I would like to refresh only if, on that page, a POST request is send.

以下内容可以帮助您理解:

Here is something that can help you to understand:

  1. 客户端正在连接到网页.
  2. SQL选择正在我的数据库上执行
  3. 结果被接收并显示在网页上.
  4. 客户端已连接(通过websockets),并从数据库中查看信息.
  5. 我.如果在数据库中插入信息,则会发送POST请求(不是从HTML表单发送,没有提交,只有POST请求,就像我使用Postman测试Web服务一样).发送请求后,通过调用Javascript函数来刷新客户端...

这是我所做的:

  • index.php (显示信息的页面)

$(document).ready(function(){

    //create a new WebSocket object.
    var wsUri = "ws://localhost:9000/server.php";
    websocket = new WebSocket(wsUri);

    websocket.onopen = function(ev) { // connection is open
        $('#message_box').append("<div class=\"system_msg\">Connected!</div>"); //notify user
    }

    // Call this function every 10 sec to refresh the client
    window.setInterval(function(){
        displayInfo(1);
    }, 10000);

    websocket.onmessage = function(ev) {
        var msg = JSON.parse(ev.data); //PHP sends Json data
        $("#infos").html(msg.message);
    };

    websocket.onerror   = function(ev){$('#message_box').append("<div class=\"system_error\">Error Occurred - "+ev.data+"</div>");};
    websocket.onclose   = function(ev){$('#message_box').append("<div class=\"system_msg\">Connection Closed</div>");};
});

function displayInfo(r) {

    $.post("infos.php",
        { refresh : r},
        function(data){

            var msg = {
                message: data
            };

            //convert and send data to server
            websocket.send(JSON.stringify(msg));
        }
    );
}

  • infos.php :在其中执行SQL选择请求的地方(工作正常)

  • infos.php : Where I execute the SQL select request (works fine)

    server.php :服务器端代码所在的位置. (效果很好)

    server.php : Where the code for the server side is. (works fine)

    好吧.我真的不知道该怎么做到.如何通知和调用函数displayInfo(r);如果POST请求发送到此页面.

    Well. I really don't know how can I achieve this. How to inform and call the function displayInfo(r); if a POST request is send to this page.

    任何帮助都非常有用.预先谢谢你.

    Any help is very appriciated. Thank you in advance.

    关于, 拉皮努.

    推荐答案

    我已经从您提供的链接中看到了server.php,它很简单:

    I've seen the server.php from the link you've provided, and it simply:

    1. 接受传入连接
    2. 遍历所有已连接的套接字
    3. 如果这些套接字中的任何一个都有数据,它将回复其他所有客户端.

    您需要更改此循环并添加其他消息来源,并且有2个选项.您可以合并一个数据库或打开另一个TCP套接字并从那里读取.

    You need to alter this loop and add another source for messages, and you have 2 options. You can pool a DB or open another TCP socket and read from there.

    但是,最好的解决方案是将NodeJS与Socket.io和DNode一起使用(非常优雅的解决方案,可以跨浏览器工作,并不难),但是您需要能够在服务器上安装NodeJS.如果您愿意,我可以提供样品.


    编辑:这是我的方法.

    However, the best solution is to use NodeJS with Socket.io and DNode (very elegant solution that works cross-browser and is not that difficult), but you need to be able to install NodeJS on your server. I can provide samples if you want.


    EDIT: Here it goes my way of doing it.

    我假设您熟悉基于Debian的发行版(我将使用APT进行安装).首先,我将解释一些事情:

    I'll assume you are familiar with Debian based distributions (I'm going to install things with APT). First I'll explain some things:

    • NodeJS 是将在服务器端运行的JavaScript解释器我们的插座部分.实际上,我们将同时使用PHP和NodeJS(后者仅用于更新客户端,因此您现有的代码不会有太大变化)
    • NPM 是一个命令行实用程序(NodeJS随附).它的主要目的是安装软件包(Socket.io和DNode是NPM软件包)
    • Socket.io 是围绕WebSocket的包装,使其可以跨浏览器工作.它还包含服务器端处理功能
    • DNode 是用于与其他语言/服务器(在这种情况下,使用我们的PHP脚本)进行通信的RPC
    • NodeJS is a server-side javascript interpreter that will run our socket part. In fact, we will use both PHP and NodeJS (the latter only for updating clients, so your existing code will not change much)
    • NPM is a command line utility (that comes with NodeJS). Its main purpose is for installing packages (Socket.io and DNode are NPM packages)
    • Socket.io is a wrapper around WebSockets that make it works cross-browser. It also contains the server-side handling functions
    • DNode is an RPC for communicating with other languages/servers (in this case, with our PHP script)

    首先,我们安装NodeJS. Ubuntu存储库上的版本非常老旧,因此我们在此处

    First we install NodeJS. The version on Ubuntu repo's is veeery old, so we add a PPA from here:

    sudo add-apt-repository ppa:chris-lea/node.js
    sudo apt-get update
    sudo apt-get install node
    

    这将安装NodeJS和NPM.更多信息此处.

    This will install NodeJS and NPM. More info here.

    现在cd进入您的工作目录并创建以下文件:server.js

    Now cd into your working directory and create this file: server.js

    //import libraries
    var io = require('socket.io');
    var dnode = require('dnode');
    
    var clients = []; //this array will hold all connected clients
    
    var srv = io.listen(8080, { log: false }); //this port must be different from apache
    srv.sockets.on('connection', function(socket){
        console.log("Client connected.");
        clients.push(socket);
    
        //this will be called when a javascript client sends us something. you can delete this if you don't need it
        socket.on('message', function(data){
            console.log(data); 
        });
    
        socket.on('disconnect', function(){
            console.log("Lost client.");
            var i = clients.indexOf(socket);
            clients.splice(i, 1); //remove from array
        });
    });
    
    var dnode_server = dnode({
        //expose a "send" function
        send: function(data, cb){
            for(i = 0; i < clients.length; i++){
                clients[i].emit('update', { //send an "update" message to all connected clients
                    title: data.title, //some data
                    text: data.text
                });
            }
            cb(null, false); //inform PHP that the processing is done. You can also return something
        }
        //you can have multiple functions here
    });
    dnode_server.listen(5004); //this port should not be accessible from the ouside
    

    下一步,安装所需的库:

    Next, install required libraries:

    npm install socket.io
    npm install dnode
    

    您可以使用node server.js

    现在,我们需要编辑客户端javascript.使用以下命令导入Socket.io:

    Now we need to edit the clientside javascript. Import Socket.io using this:

    <script type="text/javascript" src="http://YOURHOSTNAME:SOCKETIOPORT/socket.io/socket.io.js"></script>
    

    然后像这样使用它:

    socket = io.connect('http://YOURHOSTNAME:SOCKETIOPORT');
    socket.on('connect', function(data){
        alert('Connected!');
    });
    socket.on('disconnect', function(){
        alert('Disconnected :( are you offline?');
    });
    socket.on('update', function(data){ //our function call
        alert(data.title + " " + data.text);
    });
    

    您可以像在NodeJS上那样将数据发送到服务器:

    You can send data to server like on NodeJS:

    socket.emit('message', {foo: 'bar'});
    

    最后,您想从PHP脚本触发所有连接的客户端上的更新".为此,我们需要一个PHP库来连接DNode.您可以在此处找到它,其用法是很简单:

    Finally, you want to trigger "update" on all connected clients from a PHP script. For this, we need a PHP library for interfacing DNode. You can find it here and its usage is very simple:

    $dnode = new \DnodeSyncClient\Dnode();
    $connection = $dnode->connect('localhost', 5004);
    $connection->call('send', array(array(
        'title' => "My awesome title",
        'text' => "My awesome text"
    )));
    

    调用此PHP脚本会将标题和文本发送到您的server.js,它将广播所有内容到您连接的客户端.

    Calling this PHP script will send title and text to your server.js that will broadcast everything to your connected clients.

    希望这会有所帮助!

    这篇关于Websockets PHP/AJAX/Javascript刷新客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆