使用JavaScript的即时消息系统

I have a school project where i need to create an instant webbased messageing system.

Ive looked into PHP sockets to complete this task PHP socket manual

From these im starting to see a pattern. As you well know PHP can only run once (from top to bottom) and from these examples i can see that a while loop is what makes the socket listen for new connections. (meaning the php script never stops) these examples the echo the output of the socket.

as far as i can see this is great if you just want a plain site.

However this is not the case. I want to build this application using JavaScript to "ask" the socket if there is any new messages and if there is then render the messages accordingly.

Since im very new to PHP sockets im not sure if this should be done purely by PHP or if it is possible to use JavaScript to listen to the socket (via Ajax) and then print the output as a JSON?

I recommend you to use a third party library (well, an recommend you again this library: cboden/ratchet). Read its tutorials and you will have a cleaner look at how to communicate between browsers ans servers using WebSocket protocol.

The server is absolutely able to be implemented with pure PHP!

In general for push based notifications the protocol you will want (which only works with newer browsers) is WebSockets.

There are a variety of libraries and services which can do this for you:

Pusher, is an online service which can integrate with a variety of languages to give you real time functionality. https://pusher.com/

In JavaScript only, and if you have node you should look at socket.io : http://socket.io/

In .NET land, there is SignalR which is fantastic http://signalr.net/

Not only is it possible to do with PHP but it's also trivial with Thruway. Thruway is a WAMPv2 PHP client/router that uses Ratchet for the Websocket transport. WAMP gives you Sub/Pub and RPC over WebSockets.

You would need to create a simple php router and start it from the command line. Something like this:

<?php
require 'vendor\autoload.php';
use Thruway\Peer\Router;
use Thruway\Transport\RatchetTransportProvider;

$router = new Router();
$transportProvider = new RatchetTransportProvider("127.0.0.1", 9090);
$router->addTransportProvider($transportProvider);

Then on the client, use AutobahnJS or if you're using angular, you can use angular-wamp.

If you still have questions, I'll work up a simple chat example.

I actually used a PHP based websocket and adapted it. I can work both ways if you want. You can store the messages sent to the websocket in an Array or even let them be saved into a database. The client can ask for new messages:

look at this code:

    function createConnectionToWebSocket(connection)
    {
        var host = "ws://[ip of server]:9000/echobot"; // SET THIS TO YOUR SERVER --> 9000 is the port used by websockets.
        try {
                socket = new WebSocket(host);
                console.log('WebSocket - status '+socket.readyState);
                socket.onopen    = function(msg) { 
                                       console.log("Welcome - status "+this.readyState);

                                   };
                socket.onmessage = function(msg) { 
                                       messageHandlerSocket(msg.data);
                                   };
                socket.onclose   = function(msg) { 
                                       console.log("Disconnected - status "+this.readyState); 
                                       if (msg && !msg.wasClean && msg.code == 1006)
                                       {

                                       }
                                   };
                socket.onerror   = function(msg) { 

                                   };                       
            }
            catch(ex){ 
                console.log(ex); 
            }


    }

    function messageHandlerSocket(msg)
    {
        //all messages will be send in JSON
        var msg = JSON.parse(msg)
        //received JSON and check the type. Type is message
        switch (msg.type)
        {
            case "messages" :
                //code when the webserver sends back the messages.                                      

            break;
        }
   }


   socket.send(JSON.stringify({"type" : "retrievemessages", "user" : user.id}));

Socket.send allows you to send data to the PHP server. I send JSON and parse this on the server. Based on the type argument I let the PHP server send data back to the corresponding user.

I extend this webserver I found on Github.

Run the webserver via a bat-file.

@ECHO OFF
ECHO STARTING WEBSERVER
ECHO USING [dir to php dir]\php\php.exe
@ECHO OFF

START "WEBSOCKET" /wait /B "[dir to php dir]\php\v5.6\php.exe" -f [path to your websocket.php]