【问题标题】:Using Socket.io and iPhone Accelerometer使用 Socket.io 和 iPhone 加速度计
【发布时间】:2013-12-08 03:37:37
【问题描述】:

所以我目前有一个 JavaScript 代码,我在我的 iPhone 上运行它来提取它的加速度计数据。我想做的是将这些数据传递给我的 Mac Book Pro。变量每秒会更改多次,所以我正在考虑使用 Socket.io,有人知道我会怎么做吗?我将非常感谢我能得到的任何帮助。谢谢。

<html>
<body>
<div id="content">
    <h1>Accelerometer JavaScript Test</h1>
<ul>
    <li>acceleration x: <span id="accelerationX"></span></li>
    <li>acceleration y: <span id="accelerationY"></span></li>
    <li>Motor Speed: <span id="speed"></span></li>
</ul>
</div>
<script type="text/javascript">
window.ondevicemotion = function(e){
        var x = e.accelerationIncludingGravity.x;
        var y = e.accelerationIncludingGravity.y;
        var newx = x * 100
        var newy = y * 100
        var finalx = Math.round(x);
        var finaly = Math.round(y);
        document.getElementById("accelerationX").innerHTML = finalx
        document.getElementById("accelerationY").innerHTML = finaly
        speed = finalx * 10
        document.getElementById("speed").innerHTML = speed
    }
</script>
</body>
</html>

【问题讨论】:

    标签: javascript ios


    【解决方案1】:

    您需要:

    a) 在你的 macbook pro 上托管一个(websocket,可能 node.js 是最简单的)服务器,并从你的手机连接到你计算机的 IP 地址,但这只能在你的本地网络上工作。

    b) 在 AWS EC2 或 nodejitsu 之类的服务上托管一个(websocket,可能是 node.js 最简单的)服务器,然后从您的手机和计算机连接到它,然后匹配服务器端的套接字并传递数据他们之间。

    "a)" 更简单,无论哪种方式,这都应该让你开始(确保首先包含 socket.io,并在两端正确初始化它)

    在客户端:

    // set up your socket
    
    var socket = io.connect('http://' + location.host, {
         'reconnect': true,
         'reconnection delay': 50,
         'max reconnection attempts': 300
    });
    
    window.ondevicemotion = function(e){
        var x = e.accelerationIncludingGravity.x;
        var y = e.accelerationIncludingGravity.y;
        var z = e.accelerationIncludingGravity.z;
    
        // send data over the socket
        socket.emit('acceleration', {'x':x, 'y':y, 'z':z});
    }
    

    在您的(节点)服务器上:

    // set up server to listen on port 8888 - It will be accessible at YOUR.COMPS.IP.ADDR:8888 
    
    var httpServ = http.createServer(app).listen(8888, function () {
        console.log("Express server listening on port " + app.get('port'));
    });
    var io = require('socket.io').listen(httpServ, { log: true });
    
    // wait for connection
    
    io.sockets.on('connection', function (socket){
    
    // if you receive data labeled 'acceleration' from this socket then print it out
    
        socket.on('acceleration', function(data){
            console.log(data);
        });
    });
    

    【讨论】:

    • 谢谢你,但我在启动它时收到错误“ReferenceError: http is not defined”,我认为是因为 createServer 不再工作
    • 是因为没有定义。您应该查看 node.js 文档...我没有完成所有工作,您必须正确初始化您的 socket.io。 var http = require('http');应该正确初始化它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 2010-12-11
    • 1970-01-01
    相关资源
    最近更新 更多