Json Properties: Difference between revisions

Jump to navigation Jump to search
mNo edit summary
Line 124: Line 124:


=== The /PropertyListener websocket ===
=== The /PropertyListener websocket ===
The property change listener websocket also sends property objects as change events for the subscribed nodes.
The property change listener websocket also sends property objects as change events for the subscribed nodes. The following is a simple HTML page that shows its usage:


<syntaxhighlight lang="javascript">
<!-- Sample on how to use a websocket PropertyListener.                -->
<!-- Extracted from code in Phi.                                      -->
<!-- FlightGear must be started with HTTP server enabled on port 5701. -->
<!DOCTYPE html>
<html>
<body>GMT time in Flightgear: <input type="text" id="myText" value="">
<p>Click the button to launch the property listener for property /sim/time/gmt.</p>
<button onclick="myFunction()">Launch</button>


<script>
function myFunction() {
    var textfield = document.getElementById("myText");
    var ws = new WebSocket('ws://localhost:5701/PropertyListener')
    console.log('web socket readyState is ' + ws.readyState)
    ws.onopen = function (ev) {
      console.log('onopen')
      ws.send(JSON.stringify({
        command: 'addListener',
        node: 'sim/time/gmt'
      }))
    }
    ws.onmessage = function (ev) {
      try {
        var data = JSON.parse(ev.data)
        textfield.value = data.value
      } catch (e) {
        console.log('Exception in onmessage:' + e)
      }
    }
    ws.onclose = function (ev) {
      var msg = 'Lost connection to FlightGear.'
      alert(msg)
    }
    ws.onerror = function (ev) {
      var msg = 'Error communicating with FlightGear.'
      alert(msg)
    }
}
</script>
</body>
</html>
</syntaxhighlight>


== Pitfalls ==
== Pitfalls ==
183

edits

Navigation menu