我正在尝试创建一个反例,如本文所述video:- https://www.youtube.com/watch?v=jyfjfcud4ps
但是,我发现socket.io只在设置连接后更新windows。因此,我将加载该页,并且计数器不会在该页上更新,但是如果有另一个窗口打开到相同的哈希值,则该页将更新。
这是我的客户端包.json:
"name": "socketio-client",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --mode development --config ./webpack.config.js --inline --hot",
"build": "webpack"
},
"babel": {
"presets": [
"env"
]
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-preset-env": "^1.7.0",
"socket.io-client": "^2.3.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
},
"devDependencies": {
"html-webpack-plugin": "^4.3.0",
"webpack-dev-server": "^3.10.3"
}
}
这是我的客户机index.js文件side:-
import io from 'socket.io-client';
const socket = io('http://localhost:9090');
socket.on('connect', function onConnect() {
console.log('connected');
if (window.location.hash) {
const id = window.location.hash.substring(1);
console.log('hash', id);
socket.on('stats', function onStats(count) {
console.log(count);
document.getElementById('counter').innerHTML = count;
});
socket.emit('hello', { 'hashId': id });
}
});
这是我的index.htmlpage:-
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h1>Hit Counter is <span id="counter"></span></h1>
</body>
</html>
这是我的webpack.config。json:-
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: __dirname + '/src/index.html'
})
]
};
这是我的服务器端软件包。json:-
"name": "socketio-server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"redis": "^3.0.2",
"socket.io": "^2.3.0"
}
}
这是我的server.js文件(即我的服务器端可执行文件)
const io = require('socket.io')(9090);
const redis = require('redis');
const client = redis.createClient();
io.on('connection', function onConnection(socket) {
console.log('connected');
socket.on('hello', function hello(hashId) {
socket.join(hashId.hashId);
client.incr(hashId.hashId, onUpdate);
function onUpdate(err, count) {
console.log(err);
console.log(count);
socket.to(hashId.hashId).emit('stats', count);
}
});
});
我在服务器端运行node server.js,在客户端项目中运行npm run start。
然后在不同的浏览器窗口中点击以下urlhttp://localhost:8080/#asdf公司
1条答案
按热度按时间muk1a3rh1#
好的,解决了我的问题。在下面的代码中,
socket.to(hashid.hashid.emit('stats',count));应该是io.to。这是我抄写的一个错误,不是在原始视频中。