socket.io を使用してサーバー スクリプトに接続できたので、満足しています。ただし、スクリプトが生成する奇妙な動作についてはあまり満足していません。ボタンクリックでサーバー スクリプトに 1 つのエミットを送信し、サーバー テスト スクリプトがメッセージ 6x をコンソール ログに送り返します。この問題の説明をグーグルで検索すると、むらのある繰り返しの接続についてのアイデアが得られますが、それだけではないと思います。
とにかく、クライアント app.js は次のとおりです。
var commentapp={
init: function(){
var commentapp=this;
commentapp.btn_api=$('#btn_api');
commentapp.btn_api.click(this.get_comment_data);
},
get_comment_data: function(btn_event){
var commentapp=this;
console.log('trying to connect');
commentapp.socket=io.connect('http://localhost:8080');
commentapp.socket.on('connect', function() {
commentapp.socket.emit('btn_api_call');
}); //commentapp.socket.on 'connect',
commentapp.socket.on('serverMessage', function(content){
console.log(content);
}
); //commentapp.socket.on('serverMessage'
}
};
$(function() {
commentapp.init();
});
サーバースクリプトは次のとおりです。
var httpd = require("http").createServer(handler);
var io=require('/Users/user/Virtualenvs/node_modules/socket.io/lib/socket.io').listen(httpd);
var fs = require('fs');
var url = require("url");
var path = require("path");
var port = process.argv[2] || 8080;
httpd.listen(parseInt(port, 10));
function handler (request, response) {
var uri = url.parse(request.url).pathname,
filename = path.join(process.cwd(), uri);
console.log(uri);
path.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return; //these returns get you out of the function I think
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary"); //otherwise here's where the file gets finally served
response.end();
}); //fs.readFile
}); //path.exists
io.sockets.on('connection',function(socket) {
socket.on('btn_api_call', function() {
socket.emit('serverMessage', 'Server heard you.');
});
});
};
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
これらは両方とも、https://github.com/accbel/nodejs-socketio-exampleと Pedro Teixeira の本から共食いされています。
ボタンをクリックして 'btn_api_call'emit を生成すると、コンソール ログに「'サーバーがあなたを聞きました.'」と表示されます。うまくいけば、これは初歩的な間違いであり、簡単に正されます。
ご協力いただきありがとうございます!