socket.io - can't get it to work, having 404's on some kind of polling call

蓝咒 提交于 2019-11-28 06:46:25

It looks like Socket.IO can't intercept requests starting with /socket.io/. This is because in your case the listener is app -- an Express handler. You have to make http be listener, so that Socket.IO will have access to request handling.

Try to replace

app.set( "ipaddr", "127.0.0.1" );
app.set( "port", 8080 );

with

http.listen(8080, "127.0.0.1");

See docs for details: http://socket.io/docs/#using-with-express-3/4

In my case, I created my app with the Express application generator. To solve this problem, instead of edit the app.js file on the root folder of the project, I edited the file bin/www on the line after the server is defined:

/**
 * Create HTTP server.
 */

var server = http.createServer(app);
var io = require('socket.io')(server); // Add this here

Update

I found a better way here Express Generator and Socket.io

Just for check that is your server or just client problem you could use this web: websocket-echo, if this client connect right to your server (the first form client is usefull if your server is online, if is on your host, cuoting from websocket.org...

Using a text editor, copy the following code and save it as websocket.html somewhere on your hard drive

Code: websocket-test

The only thing different from mine that i could observe is the io client source: <script src="/socket.io/socket.io.js"></script> on your client side.

On your server you should try this way:

var express = require('express'), 
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server),
exec = require('child_process').exec,
util = require('util');

//serve our code
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded());
//listening on connections

io.on('connection', function (socket) {
    console.log('client connected!'); 
}
server.listen(8080);

Note that this way works fine with this dependencies: I recommend you add this code below to your package.json file:

"dependencies": {
    "express": "3.x.x",
    "socket.io": "*",
    "util": "*"
  }

cheers!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!