我建议你在 node.js 旁边使用 Socket.io。从http://socket.io/安装和下载库。您可以在 Apache 服务器旁边运行它,没有问题。
首先创建一个节点服务器:
var http = require('http')
, url = require('url')
, fs = require('fs')
, io = require('../')//path to your socket.io lib
, sys = require(process.binding('natives').util ? 'util' : 'sys')
, server;
server = http.createServer(function(req, res){
var path = url.parse(req.url).pathname;
}),
server.listen(8084);//This could be almost any port number
其次,使用以下命令从命令行运行您的服务器:
node /path/to/your/server.js
三、使用客户端js连接socket:
var socket = new io.Socket(null, {port: 8084, rememberTransport: false});
socket.connect();
您还必须包含 socket.io lib 客户端。
使用以下命令将数据从客户端发送到节点服务器:
socket.send({data:data});
您的 server.js 还应该具有处理请求的功能:
io.on('connection', function(client){
//action when client connets
client.on('message', function(message){
//action when client sends msg
});
client.on('disconnect', function(){
//action when client disconnects
});
});
有两种主要方式将数据从服务器发送到客户端:
client.send({ data: data});//sends it back to the client making the request
和
client.broadcast({ data: data});//sends it too every client connected to the server