How NodeJS and Socket.IO serve socket.io.js
I was learning NodeJS and Socket.IO through the following code from the book (Learning Node). The example worked. But I want to know how node is serving the socket.io.js file in statment <script src="/socket.io/socket.io.js"></script>
. Since there is no folder named socket.io in the root of the project, and I have not written any code to a static server file. Is this done through the Socket.IO module? Will it conflict if I use express to serve static files?
Client code
<html lang="en">
<head>
<meta charset="utf-8">
<title>bi-directional communication</title>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8124');
socket.on('news', function (data) {
var html = '<p>' + data.news + '</p>';
document.getElementById("output").innerHTML=html;
socket.emit('echo', { back: data.news });
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
server code
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
var counter;
app.listen(8124);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
counter = 1;
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { news: 'world' });
socket.on('echo', function (data) {
if (counter <= 50) {
counter++;
console.log(data.back);
socket.emit('news', {news: data.back});
}
});
});
source to share
After some reading, I got an explanation
In the server application, when the HTTP web server was created, it was passed to the Socket.IOs Listening Event:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
What's happening is Socket.IO intercepts requests sent to the web server and listens for requests:
/socket.io/socket.io.js
Socket.IO does a clever bit of behind-the-scenes purchasing that determines turned in response. If the client supports WebSockets, the JavaScript file returned is the one that uses WebSockets to implement the client connection. If the client does not support WebSockets, but does support Forever iFrame (IE9), it returns that client specific JavaScript, etc.
source to share