newguy newguy - 3 months ago 105
Node.js Question

Cannot connect to Node.js server using socket.io + express + webpack, requests return 404 errors

I am trying to test my first socket.io server/client codes. But it failed.

My HTML file is like this:

<html>
<body>
<h1>Welcome to socket project</h1>
<div id="result"></div>
<script src="https://cdn.socket.io/socket.io-1.4.8.js"></script>
<script src="./dist/main.bundle.js"></script>
</body>
</html>


My client side code is like this:

const socket = io.connect('http://localhost:9999');
console.log('Connected: ', socket.connected);
socket.emit('setPlayerPosition', {
reason: 'It\'s my birthday'
});


My server code is like this:

const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.base');
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').createServer();
const io = require('socket.io')(server);
const port = 9999;
const devPort = port - 1;
const domain = 'http://127.0.0.1:' + devPort;

const devServer = new WebpackDevServer(webpack({
devtool: 'eval',
entry: {
main: [
'webpack/hot/only-dev-server',
`webpack-dev-server/client?${domain}`,
config.entry.main
]
},
output: config.output,
plugins: config.plugins.concat([
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]),
module: config.module,
resolve: config.resolve,
}), {
publicPath: `${domain}/`,
hot: true,
historyApiFallback: true,
port: devPort,
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
});

io.on('connection', function(socket) {
socket.on('setPlayerPosition', function(id, msg) {
console.log('Position' + msg.reason);
socket.broadcast.to(id).emit('serverMsg', {
msg: 'hello'
});
});
});

app.use('/static', express.static(__dirname + '/media'));
// app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => {
res.end(
fs.readFileSync('./public/index.html')
.toString()
.replace(/\.\/dist\//g, `${domain}/`)
);
});

app.listen(port, function() {
console.log('Server is running on port', port);
});

devServer.listen(devPort);


I can connect with
http
but when I use
socket.io
it gives me a 404 error.

Failed to load resource: the server responded with a status of 404 (Not Found)
, the client side console log is "Connected: false".

How to resolve this problem?

Answer

You're creating an HTTP server to host the socket.io server:

const server = require('http').createServer();
const io = require('socket.io')(server);

However, you're not calling .listen() on that server instance, so it won't be listening on port 9999 as you might expect.

Here's an alternative setup that should work:

const port   = 9999;
const app    = express();
const server = app.listen(port, function() {
  console.log('Server is running on port', port);
});
const io = require('socket.io')(server);