我建议您将 Socket.io 与 node.js 一起使用。安装并下载库http://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连接到套接字:
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
and
client.broadcast({ data: data});//sends it too every client connected to the server