我听说nodejs是创建实时聊天应用程序的最佳选择。所以我决定尝试一下。
//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 = '';
}
};
一切似乎都不错,但是php webapp整合。我怎么能让它作为php网页的一部分工作?
答案 0 :(得分:4)
正如我在原始评论中所提到的,您可以让您的PHP应用程序继续执行它一直在做的事情,并使用NodeJS来处理Web套接字连接(通过socket.io)库。以下是您可以使用的简化结构示例:
您的chat.php
页面或聊天控制器:
<?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>
您的NodeJS应用程序如下所示。注意缺乏常规的HTTP连接处理,我们现在让PHP处理:
//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"] });
});
});
这就是你要用的基础。正如我之前在评论中提到的那样,可以扩展它以将数据库支持的身份验证机制添加到服务器的NodeJS部分。