这是我的代码
server.js
var http = require('http');
var app = require('express')();
var server = http.createServer(app).listen(process.env.PORT, process.env.IP);
var io = require('socket.io').listen(server);
var textData = "some random initial text that will be changed forever, never to be restored to its original state."
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var users = 0;
io.on('connection', function(socket){
users++;
console.log(users + " users are here.");
//broadcast recieved data
socket.on('textChange', function(text){
textData = text;
socket.broadcast.emit('updatedText', textData);
});
socket.on("disconnect", function(){
users--;
console.log(users + " users are here.");
})
});
的index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
/* global io */
var socket = io();
$(document).ready(function() {
//send value on key up
$('#textarea').keyup(function(){
socket.emit('textChange', $('#textarea').val());
});
//recieve changed value
socket.on('updatedText', function(text){
$('#textarea').val(text);
});
});
</script>
<style type="text/css">
form, form * {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<h1>HELLO</h1>
<h2></h2>
<form action="">
<textarea id="textarea"></textarea>
</form>
</body>
</html>
它按照惯例工作,但当两个人同时输入时,它会在它们之间交替出现并且只是出错。我怎样才能让两个人一起打字。 我正在考虑使用diff-patch,但我不确定它是否能解决这个问题。 请帮助。
答案 0 :(得分:0)
也许你可以添加一些用户标识符(例如sessionid或uuid或其他东西)来识别用户等:
// add user id
var user = Math.random();
$('#textarea').keyup(function(){
socket.emit('textChange', {name: user, val: $('#textarea').val()});
});
//recieve changed value
socket.on('updatedText', function(text){
if (text.user == user) {
$('#textarea').val(text.val);
}
});