How to use Socket.io and websocket for real-time data updates in Snap

Source: Internet
Author: User
Tags emit json scream setinterval

Socket.io allows our servers and clients to communicate in real-time and in both directions. It has the advantage of less data transfer than HTTP. Similarly, WebSocket has the same advantages. You can easily send your data to the server and receive event-driven responses instead of querying. In today's tutorial, let's take a look at how to use Socket.io and websocket to make a two-way communication.


1) Create a Socket.io server
First, let's take a look at one of the projects I completed:
Https://github.com/liu-xiao-guo/socketio

Let's take a look at our Snapcraft.yaml files first:
Snapcraft.yaml

Name:socketio
Version: "0.1" summary:a simple shows what to do use of
socket IO
description:socket.io snap Example

grade:stable
confinement:strict

Apps:
  socket:
    command:bin/socketio
    Daemon: Simple
    plugs: [Network-bind]

parts:
  nod:
    plugin:nodejs
    Source:.
   

This is a Nodejs project. We used Nodejs's plugin. Our Package.json file is as follows:
Package.json
{
  "name": "Socketio",
  "version": "0.0.1",
  "description": "Intended as a Nodejs app in a snap",
  "license" : "GPL-3.0",
  "author": "Xiaoguo, Liu",
  "private": true,
  "bin": "./app.js",
  "dependencies": {
    " Express ":" ^4.10.2 ","
    nodejs-websocket ":" ^1.7.1 ",
    " Socket.io ":" ^1.3.7 "
  }
}

Since we need to use to webserver, all we have installed the Express architecture package. In addition, we use the Socket.io and WebSocket, all of which we have put into our snap package.
Take a look at the design of our application App.js:
App.js
#!/usr/bin/env node var express = require (' Express ');
var app = require (' Express ') (); var http = require (' http ').
Server (APP);	

var io = require (' Socket.io ') (HTTP);

App.get ('/', function (req, res) {res.sendfile (__dirname + '/www/index.html ');});

App.use (express.static (__dirname + '/www '));
  
  Whenever someone connects this gets executed Io.on (' connection ', function (socket) {console.log (' A user connected ');
	  SetInterval (function () {var value = Math.floor ((math.random () * 1000) + 1);
	  Io.emit (' Light-sensor-value ', ' + value ');
  Console.log ("Value:" + value)//This is another-to send data socket.send (value); 

  }, 2000);  Whenever someone disconnects this piece of code executed Socket.on (' Disconnect ', function () {console.log (' A user
  Disconnected ');

});

});

Http.listen (4000, function () {Console.log (' listening on *:4000 ');}); var ws = Require ("Nodejs-websocket") Console.log ("Going to create the server") String.prototype.format = FuNction () {var formatted = this;
        for (var i = 0; i < arguments.length; i++) {var regexp = new RegExp (' \\{' +i+ ' \ \} ', ' GI ');
    formatted = Formatted.replace (RegExp, arguments[i]);
} return formatted;
 
}; 
Scream Server Example: "Hi", "Hi!!!"
    
    var server = Ws.createserver (function (conn) {Console.log ("New connection") var connected = true;
    Conn.on ("Text", function (str) {Console.log ("Received" +str) Conn.sendtext (str.touppercase () + "!!!")
    }) Conn.on ("Close", function (code, reason) {Console.log ("Connection closed") connected = False
	  }) SetInterval (function () {var value = Math.floor ((math.random () * 1000) + 1);
	  var data = ' {' data ': ' {0} '} '. Format (value) if (connected) {conn.send (data); 	
}}, 2000);
 }). Listen (4001)

In the first part of the code, we created a webserver that uses a port address of 4000. We also started the Socket.io server at the same time, waiting for the client to connect. Once there is a connection, we use the following code to send some data every time:
Whenever someone connects this gets executed
io.on (' Connection ', function (socket) {
  console.log (' A user Connected ');
  
  SetInterval (function () {
	  var value = Math.floor ((math.random () * +) + 1);
	  Io.emit (' Light-sensor-value ', ' + value ');
	  Console.log ("Value:" + value)
	  
	  //This is another-
  to 

  send data socket.send (value); Whenever someone disconnects this piece of code executed
  socket.on (' Disconnect ', function () {
    Console.log (' A user disconnected ');});


Although these data are random, we are mainly used to show how it works. In practical applications, these data can be obtained from some sensors. In our client, we can open the address of the webserver run:

We can see that the data is constantly coming in and showing up in our client. Please refer to the index.html file in the WWW directory for the specific design.


2) Create a websocket server
In our app.js, we use the following code to implement a WebSocket server. The port address is 4001.
App.js
var ws = Require ("Nodejs-websocket") Console.log ("Going to create the server") String.prototype.forma
    t = function () {var formatted = this;
        for (var i = 0; i < arguments.length; i++) {var regexp = new RegExp (' \\{' +i+ ' \ \} ', ' GI ');
    formatted = Formatted.replace (RegExp, arguments[i]);
} return formatted;
 
}; 
Scream Server Example: "Hi", "Hi!!!"
    
    var server = Ws.createserver (function (conn) {Console.log ("New connection") var connected = true;
    Conn.on ("Text", function (str) {Console.log ("Received" +str) Conn.sendtext (str.touppercase () + "!!!")
    }) Conn.on ("Close", function (code, reason) {Console.log ("Connection closed") connected = False
	  }) SetInterval (function () {var value = Math.floor ((math.random () * 1000) + 1);
	  var data = ' {' data ': ' {0} '} '. Format (value) if (connected) {conn.send (data); 	
}}, 2000); }). Listen (4001) 

Similarly, once there is a connection, we send a data to our client every two seconds. To illustrate the problem, we designed a QML client.
MAIN.QML
Import QtQuick 2.4 Import ubuntu.components 1.3 Import Ubuntu.Components.Pickers 1.3 Import qt.websockets 1.0 Import Qtqui Ck.

    Layouts 1.1 MainView {//ObjectName for functional testing purposes (AUTOPILOT-QT5) ObjectName: "MainView" note! ApplicationName needs to match the "name" field of the click Manifest ApplicationName: "Dialer.liu-xiao-guo" Widt
        H:units.gu (height:units.gu) function Interpretedata (data) {var json = json.parse (data)
    Console.log ("Websocket data:" + data) Console.log ("Value:" + json.data) Mainhand.value = Json.data } WebSocket {Id:socket url:input.text ontextmessagereceived: {console.log ("so
            Mething is received!: "+ message);
                Interpretedata (Message)} onstatuschanged: {if (socket.status = = Websocket.error) { Console.log ("Error:" + socket.errorstring)} else if (Socket.statUS = = Websocket.open) {//Socket.sendtextmessage ("Hello World ...")} else if (socket.status
            = = websocket.closed) {}} Active:true} Page {header:pageheader { Id:pageheader title:i18n.tr ("dialer")} Item {anchors {t Op:pageHeader.bottom Left:parent.left right:parent.right bottom:parent
                . Bottom} Column {anchors.fill:parent spacing:units.gu (1) Anchors.topMargin:units.gu (2) Dialer {Id:dialer si Ze:units.gu () minimumvalue:0 maximumvalue:1000 Anchors.ho
                        RizontalCenter:parent.horizontalCenter Dialerhand {Id:mainhand OnvaluechanGed:console.log (Value)}} TextField {Id:inpu

                T width:parent.width text: "Ws://192.168.1.106:4001"}
        Label {Id:value Text:mainHand.value}}
 }
    }
}

To run our servers and clients:


We can see that our values are constantly changing. The code for this client is in: Https://github.com/liu-xiao-guo/dialer
In this article, we show how to use Socket.io and websocket to communicate in both directions in real time. In many IoT applications, we can leverage these communications protocols to better design our applications.
Read MORE: Https://github.com/snapcore/snapcraft/tree/master/demos/webchat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.