gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:35:52 26 4
gpt4 key购买 nike

我正在尝试测试我的第一个 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 错误。

无法加载资源:服务器响应状态为 404(未找到),客户端控制台日志为“Connected: false”。

如何解决这个问题?

最佳答案

您正在创建一个 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);

关于node.js - 使用socket.io + express + webpack无法连接Node.js服务器,请求返回404错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39079099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com