0

I've heard that nodejs is the best choice for creating real-time chat application. So I decide to try one.

//on server side
//create nodejs server
var http = require('http');

var chatApp = http.createServer(function (request, response) {
    //create an html chat form listened by this nodejs server
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write('<script src="http://localhost/nodejs/app/socket.io.js"></script><script src="http://localhost/nodejs/app/chat.client.js"></script><input type="text" id="message_input"><div id="chatlog"></div>');
    response.end();
}).listen(8000);
//create websocket protocol via socket.io
var io = require('socket.io').listen(chatApp);
//send data to client
io.sockets.on('connection', function(socket) {
    socket.on('message_to_server', function(data) {
        io.sockets.emit("message_to_client",{ message: data["message"] });
    });
});
//on client side
//get data from server response
var socketio = io.connect();
socketio.on("message_to_client", function(data) {
    document.getElementById("chatlog").innerHTML = ("<hr/>" +
    data['message'] + document.getElementById("chatlog").innerHTML);
});
//submit and send data to server via enter key
document.onkeydown = function(e){
    var keyCode = (window.event) ? e.which : e.keyCode;
    if(keyCode == 13){
        var msg = document.getElementById("message_input").value;
        socketio.emit("message_to_server", { message : msg});
        document.getElementById("message_input").value = '';
    }
};

Everything seems ok but php webapp intergration. How could I make it work as a part of a php web page?

3
  • You could delegate your PHP script to handle rendering of the chat user interface, and let NodeJS + the Socket.io server handle the chat messages. You can also make use of a database that both your PHP script and NodeJS application have access to, if data needs to be shared between the two services. Commented May 16, 2014 at 17:12
  • Could you make an example on server side? I don't know how to make nodejs server listen to HTML form rendered by PHP. I greatly appreciate that. Commented May 16, 2014 at 17:16
  • just take your client side stuff put it in its own js file and include it along with your other js files in your html. in your js change this to var socketio = io.connect('http://somehost:8000'); Commented May 16, 2014 at 17:25

1 Answer 1

5

As mentioned in my original comment, you can let your PHP application continue doing what it has been doing all along and just use NodeJS for handling web socket connections (via the socket.io) library. Here is an example of a simplified structure you could use:

Your chat.php page or Chat controller:

<?php
// Handle /chat route
// Perform any authentication with your database
// Render template
?>
<!-- The following HTML is rendered -->
<html>
  <head>
    ...
    <script src="http://localhost/nodejs/app/socket.io.js"></script>
    <script src="http://localhost/nodejs/app/chat.client.js"></script>
  </head>
  <body>
    ...
    <input type="text" id="message_input">
    <div id="chatlog"></div>
    ...
    <script>
    var socketio = io.connect('http://localhost:8080');
    socketio.on("message_to_client", function(data) {
        document.getElementById("chatlog").innerHTML = ("<hr/>" +
        data['message'] + document.getElementById("chatlog").innerHTML);
    });
    //submit and send data to server via enter key
    document.onkeydown = function(e){
        var keyCode = (window.event) ? e.which : e.keyCode;
        if(keyCode == 13){
            var msg = document.getElementById("message_input").value;
            socketio.emit("message_to_server", { message : msg});
            document.getElementById("message_input").value = '';
        }
    };
    </script>
  </body>
</html>

Your NodeJS application would look like the following. Note the lack of regular HTTP connection handling, which we now let PHP handle:

//create websocket protocol via socket.io
var io = require('socket.io').listen(8080);
//send data to client
io.sockets.on('connection', function(socket) {
  socket.on('message_to_server', function(data) {
    io.sockets.emit("message_to_client",{ message: data["message"] });
  });
});

And that is the base you would use. As mentioned before in my comment, it is possible to extend this to add database-backed authentication mechanisms to the NodeJS portion of the server.

Sign up to request clarification or add additional context in comments.

6 Comments

I still don't get how socket.io communicate with server. Because chatApp no longer exist in this line var io = require('socket.io').listen(chatApp);.
@Orion: You are right; I had forgotten a piece of the code. The example should be more clear now.
I've tried your method. And it output an error http://localhost/socket.io/?EIO=2&transport=polling 404 (Not Found). Do you know where does this come from?
@Orion: You may have to explicitly define the server URL in your client's io.connect function (e.g. io.connect('http://localhost:8080')).
Thank you so much. It worked greatly. I don't know what to say. Just Very very big thanks for your answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.