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
3 番目に、クライアント側の 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
});
});
サーバーからクライアントにデータを送信するには、主に次の 2 つの方法があります。
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