Socket.io and Express3 - 404 on client request / socket.io / socket.io.js

I get 404 when I try to resolve '/socket.io/socket.io.js' from my Node server. I canโ€™t determine why.

My server configuration is as follows:

var express = require('express') , engine = require('ejs-locals') , app = express() , http = require('http') , server = http.createServer(app) , io = require('socket.io').listen(server); // use ejs-locals for all ejs templates: app.engine('ejs', engine); app.set('views',__dirname + '/views'); app.set('view engine', 'ejs'); // so you can render('index') app.use(express.static(__dirname + '/public')); //define routes ... app.listen(3000); //socket io io.sockets.on('connection', function (socket) { socket.on('set nickname', function (name) { socket.set('nickname', name, function () { socket.emit('ready'); }); }); socket.on('msg', function () { socket.get('nickname', function (err, name) { console.log('Chat message by ', name); }); }); }); 

I have a client:

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

I am testing this locally (port: 3000). The socket code is basically ripped off from the socket.io example to get something working. I looked through other posts and cannot find where I am mistaken. Can anyone help?

thanks

+4
source share
1 answer

Got it!

In this case, the HTTP server should be specified on the port (in this case 3000.) Then I deleted app.listen (3000), since the address will already be used and not needed.

Thanks!

 var express = require('express') , engine = require('ejs-locals') , app = express() , http = require('http') , server = http.createServer(app).listen(3000) , io = require('socket.io').listen(server); 
+7
source

Source: https://habr.com/ru/post/1482787/


All Articles