最初のsocket.ioサーバー/クライアントコードをテストしようとしています。しかしそれは失敗した。socket.io + express + webpackを使用してNode.jsサーバーに接続できません。要求は404エラーを返します。
私の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)
の場合、クライアント側のコンソールログは "Connected:false"です。
この問題を解決するにはどうすればよいですか?
404:
ここで動作するはずの代替設定ですか? – robertklep
@robertklep通常のリクエストです。 'http:// localhost:9999' – newguy