realTimeEditorDemo

  1. 1. 文本编辑器的实时共享编辑

文本编辑器的实时共享编辑

基于 socket.io 和 codemirror实现简单的demo

  • server端收到update消息后广播到其它所有客户端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
io.on('connection', function (socket) {
socket.emit('doc', {
timestamp: new Date().getTime(),
doc: file
})
socket.on('update', function (data) {
file = data.doc;
io.emit('doc', data);
})
socket.on('disconnect', function (data) {
console.log('disconnect', data)
})
});
  • 客户端检测到变化时触发发送update消息,收到新的doc时更新当前内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
socket.on('doc', (data) => {
const { timestamp, doc } = data
if (timestamp > this.currentDoc.timestamp) {
this.currentDoc = { timestamp, doc };
if (doc !== this.codemirror.getValue()) {
this.codemirror.setValue(doc)
}
}
});
this.codemirror.on('change', (...args) => {
socket.emit('update', {
timestamp: new Date().getTime(),
doc: this.codemirror.getValue()
})
})

完整代码见 realTimeEditorDemo