Node + Socket.io Connection issue

2019-09-17 21:49发布

问题:

I'm having trouble connecting to socket.io. With the code below, I keep getting an 'io is not defined' error on my browser console. Anyone have any idea what I'm doing wrong here? I've been poking around stackoverflow for hours, but no solution seems to work...

server side:

,db = require("../../lib/db")
,config = require("../../config")
,app = require("../index")
,io = require('socket.io')(app);
;
io.on('connection', function (socket) {
    console.log('connected')
});

exports.render = function(req, res){
    console.log(io)
    res.render("vitron", {});
}

client side:

<!doctype html>
<html>
<head>
 <title>Sockets</title>
 <script src="/socket.io/socket.io.js"></script>
 <script>
 var socket = io.connect('http://localhost');
socket.on('news', function (data) {
 console.log(data);
 socket.emit('my other event', { my: 'data' });
});
 </script>
</head>
<body>
</body>
</html>

回答1:

You apparently don't have the right server-side initialization so that your server will automatically serve the /socket.io/socket.io.js file.

There are many ways to do this, but the simplest way that is documented in the socket.io documentation is to use some built-in middleware that will have the socket.io server-side library automatically intercept the request for the /socket.io/socket.io.js file and serve up the script file.

The socket.io documentation shows exactly how to do this when using express with node. If you aren't using express, then you can do it with your own middleware. Or, if you're just using plain node, you will have to either handle that route yourself or just put the /socket.io/socket.io.js file in a known location that it can be requested directly from. You can even link to it on a CDN if you want, but there is an advantage to using the built-in scheme because when/if you upgrade the socket.io library on the server, it will automatically contain a matching client-side library which is kind of nice.

I don't know exactly what your overall setup is, but here's my socket.io initialization with express 4.

var express = require('express');
var app = express();
var server = app.listen(8081, function() {
    console.log(new Date().toISOString() + ": server started on port 8081");
});
var io = require('socket.io').listen(server);