第一次使用 node js,我正在编写一个供我和 friend 之间私有(private)使用的应用程序,我的 friend 可以随时加入。
是否可以让服务器有一个对象数组 a.e. 'franksLibrary' 有 n 个项目
并且用户能够阅读和修改“franksLibrary”?
目前我所做的是在用户网页中设置“franksLibrary”并发送 franksLibrary 和所有其他变量以通过 socket.io 同步
index.js 是服务端代码, index.html 是传递给用户的内容
示例 index.js
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg, usr){
io.emit('chat message',msg, usr);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
示例 index.html:
var franksLibrary = [{
"book1":"title of book 1"
},
{
"book2":"title of book 2"
}];
socket.on('chat message', function(franksL /*,more variables*/){
franksLibrary = franksL
});
synch = function(){
socket.emit('chat message', franksLibrary /*,more variables*/);
}
removeBook = function(object, from){
var a = object;
var index = from.indexOf(a);
from.splice(index,1);
synch();
}
最佳答案
将 franksLibrary
从 index.html
移动到 index.js
。然后,在服务器的 connection
回调中,将带有数据的 chat message
发送到新连接的客户端。
索引.js
var franksLibrary = [{
"book1": "title of book 1"
},
{
"book2": "title of book 2"
}];
io.on('connection', function(socket) {
socket.emit('chat message', franksLibrary);
socket.on('chat message', function(data) {
franksLibrary = data;
socket.broadcast.emit('chat message', franksLibrary);
});
});
index.html
// initialize variable
var franksLibrary = [];
const socket = io();
socket.on('chat message', function(franksL) {
franksLibrary = franksL;
});
const synch = function(){
socket.emit('chat message', franksLibrary);
};
const removeBook = function(object, from) {
var a = object;
var index = from.indexOf(a);
from.splice(index,1);
synch();
};
关于javascript - Socket.io - 在服务器和客户端之间同步数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58827033/