2013-12-08 78 views
0

所以我目前有一個JavaScript代碼,我在我的iPhone上運行它來提取其加速度計數據。我想要做的是將這些數據傳遞給我的Mac Book Pro。變量每秒都在變化多次,所以我正在考慮使用Socket.io,有沒有人知道我會怎麼做呢?我將不勝感激任何幫助,我可以得到。謝謝。使用Socket.io和iPhone加速度計

<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> 

回答

1

您需要:

一)主持(WebSocket的,大概是的Node.js在您的MacBook Pro最簡單的)服務器,並從你的手機連接到您的計算機的IP地址,但是這樣會只能在您的本地網絡上運行。

b)在AWS EC2或nodejitsu等服務上託管a(websocket,可能是node.js最簡單)服務器,並從您的電話和計算機連接到服務器,然後匹配服務器端的套接字並通過他們之間的數據。

「一)」更簡單,這應該讓你開始無論哪種方式(確保包括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); 
    }); 
}); 
+0

謝謝你,但我得到的錯誤「的ReferenceError:HTTP是沒有定義」當我開始了,我想是因爲createServer不再起作用 – user3078477

+0

這是BEC因爲它沒有被定義。你應該看看node.js文檔......我沒有做所有的工作,你必須正確地初始化你的socket.io。 var http = require('http');應該正確初始化它 – samfr