无法使用socket.io + express + webpack连接到Node.js服务器,请求返回404错误

时间:2016-08-22 12:05:20

标签: node.js express socket.io

我正在尝试测试我的第一个socket.io服务器/客户端代码。但它失败了。

我的HTML文件是这样的:

<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>

我的客户端代码是这样的:

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

我的服务器代码是这样的:

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);

我可以与http联系但是当我使用socket.io时,它会给我404错误。

Failed to load resource: the server responded with a status of 404 (Not Found),客户端控制台日志为&#34;已连接:false&#34;。

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

您正在创建一个HTTP服务器来托管socket.io服务器:

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

但是,您并未在该服务器实例上调用.listen(),因此它不会像您预期的那样在端口9999上进行侦听。

这是一个应该有效的替代设置:

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);