通过socket.io发送var

时间:2019-02-02 11:44:02

标签: javascript socket.io

ii是node.js和socket.io的新手。我正在尝试跟踪手机到PC的手势。我正确发送了文本,但无法发送数据

index.html

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <body ontouchstart="showCoordinates(event)" ontouchmove="showCoordinates(event)"> -->
<body ontouchstart="countTouches(event)" ontouchend="countTouches(event)">
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
function countTouches(event) {
var x = event.touches.length;
socket.emit('clicked');
}
socket.on('buttonUpdate', function(countTouches){
document.getElementById("demo").innerHTML = x;
});
</script>

</body>
</html>

server.js

io.on('connection', function(client){
client.on('clicked', function(data) {
//send a message to ALL connected clients
io.emit('buttonUpdate');
console.log('click!');
  });
});
http.listen(3000, function() {
    console.log('listening on localhost:3000');
});

我的手机上有触摸计数,但电脑上有错误 控制台错误:未捕获ReferenceError:未定义x

1 个答案:

答案 0 :(得分:0)

您不是从服务器发送数据,而是在客户端接收countTouches,但提供的值为x。尝试下面的代码。

io.on('connection', function(client){
client.on('clicked', function(data) {
//send a message to ALL connected clients
console.log(data);
io.emit('buttonUpdate',data);
console.log('click!');
  });
});
http.listen(3000, function() {
    console.log('listening on localhost:3000');
});
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <body ontouchstart="showCoordinates(event)" ontouchmove="showCoordinates(event)"> -->
<body ontouchstart="countTouches(event)" ontouchend="countTouches(event)">
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
function countTouches(event) {
var x = event.touches.length;
socket.emit('clicked',x);
}
socket.on('buttonUpdate', function(countTouches){
document.getElementById("demo").innerHTML = countTouches;
});
</script>

</body>
</html>