Just came across this question, and another just like it with a much better answer.
https://stackoverflow.com/a/14118102/1068746
You can do server to server. The "client" code remains the same as if it was on the browser. Amazing isn't it?
I just tried it myself, and it works fine..
I ran 2 servers - using the same exact code - once on port 3000 as server, and another on port 3001 as client. The code looks like this:
, io = require('socket.io')
, ioClient = require('socket.io-client')
....
if ( app.get('port') == 3000 ){
io.listen(server).sockets.on('connection', function (socket) {
socket.on('my other event', function (data) {
console.log(data);
});
});
}else{
function emitMessage( socket ){
socket.emit('my other event', { my: 'data' });
setTimeout(function(){emitMessage(socket)}, 1000);
}
var socket = ioClient.connect("http://localhost:3000");
emitMessage(socket);
}
And if you see on the server side a "{my:data}" print every second, everything works great. Just make sure to run the client (port 3001) after the server (port 3000).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…