简体   繁体   中英

create nodejs chat on php web application

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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