====== WebSocket ======
WebSocket is a protocol for bidirectional communication between a web application and a server via a TCP connection.\\
Netzer uses WebSocket as a channel for the [[commandinterface|command interface]].
====== Why WebSocket? ======
In normal HTTP a client (i.e. the browser) sends a request to a server. After some processing time the server responses to the client. This is one way, the server can not serve files or data by itself without been requested before.
This is a disadvantage i.e. if data must be asynchronously refreshed. In such cases the client has to poll the server which leads to a lot of traffic.
WebSocket are a possibilty for bidirectional communication between server and client. Client and server can send data on demand - Both are equal communication partners. While refreshing data it is enough to send data as soon they are available. It is not necessary anymore to poll the server.
var myWebSocket = new WebSocket(myWebSocketURI);
In some Firefox versions (till version 11) the WebSocket object has the name "MozWebSocket". All other names are equal (if implemented). An appropriate information which browser currently support WebSockets can be found here: [[wp>WebSocket#Browser_support]].
var myWebSocket = new MozWebSocket(myWebSocketURI);
===== Send data =====
WebSockets support two fundamental transmission types: Text (UTF-8) and binary. Data is send with ''send(myData)''. The tranmission type is chosen through the data type of ''myData''.
Netzer currently only supports text transmissions, thats why only this transmission type is shown here.
The text transmission type is only used, if the parameter for ''send'' is a string.
var myData = "My text is here.";
myWebSocket.send(myData);
===== Receive data =====
Receiving data is handled via an event handler ''onmessage''. ''event.data'' contains the received data.
myWebSocket.onmessage = function(event) {alert("Received data: "+event.data);};
===== Close connection =====
To close the WebSocket connection, the function ''close()'' must be called. Optional a closing code and a reason can be given. Both of them are currently not interpreted by Netzer.
myWebSocket.close();
===== Further event handler =====
==== onopen ====
''onopen'' is fired, if a WebSocket connection is opened.
==== onclose ====
''onclose'' is fired, if a WebSocket connection is closed. The close code and reason from server can be requested with ''close'' or ''reason''.
myWebSocket.onclose = function(event) {alert("Connection closed. Code: "+event.code+" Reason: "+event.reason);};
==== onerror ====
''onerror'' is fired, if an error has occured.
===== A simple example =====
Showing the current value of the Netzer pin IO0.