简体   繁体   English

通过socket.io发送var

[英]Sending var over socket.io

ii'm new to node.js and socket.io. ii是node.js和socket.io的新功能。 I'm trying to track gesture from phone to pc. 我正在尝试跟踪手机到PC的手势。 I'm correctly sending text but i'm not able to send data 我正在正确发送文本,但无法发送数据

index.html 的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 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');
});

I got the touch count in my phone but error in the pc Error from console: Uncaught ReferenceError: x is not defined 我在手机中得到了触摸计数,但在PC中出现错误控制台出现错误:Uncaught ReferenceError:未定义x

You are not sending the data on emit from the server and in the client you are receiving countTouches but providing value of x . 您没有从服务器发送数据,而是在客户端接收countTouches但是提供了x值。 Try with the below code. 请尝试以下代码。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM