How NodeJS and Socket.IO serve socket.io.js

2019-05-11 07:22发布

I was learning NodeJS and Socket.IO via following code from a book(Learning Node). The example worked. But I want to know how the node is serving the socket.io.js file in the statment <script src="/socket.io/socket.io.js"></script> Because there is no folder named socket.io in the project root and I don't have any code written to server static file. Is this done via Socket.IO module? Will it conflict if I use express to serve static files?

Client Side 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 side 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});
        }
    });
});

1条回答
祖国的老花朵
2楼-- · 2019-05-11 07:34

After some reading I got the explanation

In the server application, when the HTTP web server was created, it was passed to the Socket.IO’s listen event:

var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)

What happens is that Socket.IO intercepts requests sent to the web server and listens for requests for:

/socket.io/socket.io.js

Socket.IO does a clever bit of behind-the-scenes finagling that determines what’s re- turned in the response. If the client supports WebSockets, the JavaScript file returned is one that uses WebSockets to implement the client connection. If the client doesn’t support WebSockets, but does support Forever iFrame (IE9), it returns that particular JavaScript client code, and so on.

查看更多
登录 后发表回答