It’s just data

Realtime Updates of Web Content Using WebSockets

Preface

You've seen web sites with stock prices or retweet counts that update in real time. However, such sites are more the exception rather than the norm. WebSockets make it easy, and are widely supported, but not used as much as they could be.

Examples provided for WebSockets typically don't focus on the "pubsub" use case; instead they tend to focus on echo servers and the occasional chat server. These are OK as far as they go.

This post provides three mini-demos that implement the same design pattern in JavaScript on both the client and server.

Quick Start

For the impatient who want to see running code,

git clone https://github.com/rubys/websocket-demo.git
cd websocket-demos
npm install
node server.js

After running this, visit http://localhost:8080/ in a browser, and you should see something like this:

header

  • one
  • two
  • three

Server support

The primary responsibility of the server is to maintain a list of active websocket connections. The code below will maintain three such sets, one for each of the demos provided.

// attach to web server
var wsServer = new websocket.server({httpServer: httpServer});

// three sets of connections
var connections = {
  text: new Set(),
  html: new Set(),
  json: new Set()
};

// when a request comes in for one of these streams, add the websocket to the
// appropriate set, and upon receipt of close events, remove the websocket
// from that set.
wsServer.on('request', (request) => {
  var url = request.httpRequest.url.slice(1);

  if (!connections[url]) {
    // reject request if not for one of the pre-identified paths
    request.reject();
    console.log((new Date()) + ' ' + url + ' connection rejected.');
    return;
  };

  // accept request and add to the connection set based on the request url
  var connection = request.accept('ws-demo', request.origin);
  console.log((new Date()) + ' ' + url + ' connection accepted.');
  connections[url].add(connection);

  // whenever the connection closes, remove connection from the relevant set
  connection.on('close', (reasonCode, description) => {
    console.log((new Date()) + ' ' + url + ' connection disconnected.');
    connections[url].delete(connection)
  })
});

The code is fairly straightforward. Three sets are defined; and when a request comes in it is either accepted or rejected based on the path part of the URL of the request. If accepted, the connection is added to the appropriate set. When a connection is closed, the connection is removed from the set.

EZPZ!

Client Support

The client's responsibitlity is to open the socket, and to keep it open.

function subscribe(path, callback) {    
  var ws = null;
  var base = window.top.location.href

  function openchannel() {
    if (ws) return;
    var url = new URL(path, base.replace('http', 'ws'));
    ws = new WebSocket(url.href, 'ws-demo');

    ws.onopen = (event) => {
      console.log(path + ' web socket opened!');
    };

    ws.onmessage = (event) => {
      callback(event.data);
    };

    ws.onerror = (event) => {
      console.log(path + ' web socket error:');
      console.log(event);
      ws = null;
    };

    ws.onclose = (event) => {
      console.log(path + ' web socket closed');
      ws = null;
    }
  }

  // open (and keep open) the channel
  openchannel();
  setInterval(() => openchannel(), 2000);
}

A subscribe method is defined that accepts a path and a callback. The path is used to construct the URL to open. The callback is called whenever a message is received. Errors and closures cause the ws variable to be set to null. Every two seconds, the ws variable is checked, and an attempt is made to reestablish the socket connection when this value is null.

First example - textarea

Now it is time to put the sets of server connections, and client subscribe function to use.

Starting with the client:

var textarea = document.querySelector('textarea');

// initially populate the textarea with the contents of data.txt from the
// server
fetch("/data.txt").then((response) => {
  response.text().then((body) => { textarea.value = body })
});

// whenever the textarea changes, send the new value to the server
textarea.addEventListener('input', (event) => {
  fetch("/data.txt", {method: 'POST', body: textarea.value});
});

// whenever data is received, update textarea with the value
subscribe('text', (data) => { textarea.value = data });

The value of the textarea is fetched from the server on page load. Changes made to the textarea are posted to the server as they occur. Updates received from the server are loaded into the textarea. Nothing to it!

Now, onto the server:

// Return the current contents of data.txt
app.get('/data.txt', (request, response) => {
 response.sendFile(dirname + '/data.txt');
});

// Update contents of data.txt
app.post('/data.txt', (request, response) => {
 var fd = fs.openSync(dirname + '/data.txt', 'w');
 request.on('data', (data) => fs.writeSync(fd, data));
 request.on('end', () => {
   fs.closeSync(fd);
   response.sendFile(dirname + '/data.txt');
 })
})

// watch for file system changes.  when data.txt changes, send new raw
// contents to all /text connections.
fs.watch(dirname, {}, (event, filename) => {
  if (filename == 'data.txt') {
    fs.readFile(filename, 'utf8', (err, data) => {
      if (data && !err) {
        for (connection of connections.text) {
          connection.sendUTF(data)
        };
      }
    })
  }
})

Requests to get data.txt cause the contents of the file to be returned. Post requests cause the contents to be updated. It is the last block of code that we are most interested in here: the file system is watched for changes, and whenever data.txt is updated, it is read and the results are sent to each text connection. Pretty straightforward!

If you visit http://localhost:8080/textarea in multiple browser windows, you will see a textarea in each. Updating any one window will update all. What you have is the beginning of a collaborative editing application, though there would really need to be more logic put in place to properly serialize concurrent updates.

Second example - markdown

The first example has the server sending plain text content. This next example deals with HTML. The marked package is used to convert text to HTML on the server.

This client is simpler in that it doesn't have to deal with sending updates to the server:

// initially populate the textarea with the converted markdown obtained
// from the server
fetch("/data.html").then((response) => {
  response.text().then((body) => { document.body.innerHTML = body })
});

// whenever data is received, update body with the data
subscribe('html', (data) => { document.body.innerHTML = data });

The primary difference between this example and the previous one is that the content is placed into document.body.innerHTML instead of textarea.value.

Like the client, the server portion of this demo consists of two blocks of code:

app.get('/data.html', (request, response) => {
  fs.readFile('data.txt', 'utf8', (error, data) => {
    if (error) {
      response.status(404).end();
    } else {
      marked(data, (error, content) => {
        if (error) {
          console.log(error);
          response.status(500).send(error);
        } else {
          response.send(content);
        }
      })
    }
  })
});

// watch for file system changes.  when data.txt changes, send converted
// markdown output to all /html connections.
fs.watch(dirname, {}, (event, filename) => {
  if (filename == 'data.txt') {
    fs.readFile(filename, 'utf8', (err, data) => {
      if (data && !err) {
        marked(data, (err, content) => {
          if (!err) {
            for (connection of connections.html) {
              connection.sendUTF(content);
            }
          }
        }) 
      }
    })
  }
})

The salient difference between this example and the previous example is call to the marked function to perform the conversion.

If you visit http://localhost:8080/markdown, you will see the text converted to markdown. You can also visit http://localhost:8080/ to see both of these demos side by side, in separate frames. Updates make in the window on the left will be reflected on the right.

No changes were required to the first demo to make this happen as both demos watch for file system changes. In fact, you can edit data.txt on the server with your favorite text area and whenever you save your changes all clients will be updated.

Final example - JSON

In this final example, the server will be sending down a recursive directory listing, complete with file names, sizes, and last modified dates. On the client, Vue.js will be used to present the data. We start with a template:

<tbody>
  <tr v-for="file in filelist">
    <td>{{ file.name }}</td>
    <td>{{ file.size }}</td>
    <td>{{ file.mtime }}</td>
  </tr>
</tbody>

And add a bit of code:

var app = new Vue({el: 'tbody', data: {filelist: []}});

fetch('filelist.json').then((response) => {
  response.json().then((json) => { app.filelist = json });
});

subscribe('json', (data) => { app.filelist = JSON.parse(data) });

The first line associates some data (initially an empty array) with an HTML element (in this case tbody). The remaining code should look very familiar by now. Because of the way Vue.js works, all that is required to update the display is to update the data.

The server side should also seem pretty familiar:

app.get('/dir.json', (request, response) => {
  response.json(stats(dirname));
});

fs.watch(dirname, {recursive: true}, (event, filename) => {
  var data = JSON.stringify(stats(dirname));
  for (connection of connections.json) {
    connection.sendUTF(data)
  }
})

Not shown is the code that extracts the information from the filesystem, the rest is the same basic pattern that has been used for each of these demos.

If you visit http://localhost:8080/filelist, you will see a table showing each of the files on the server. This list will be updated whenever you create, delete, or update any file. The server will push a new (and complete) set of data, and Vue.js will determine what needs to be changed in the browser window. All this generally takes place in a fraction of a second.

Vue.js is only one such framework that can be used in this way. Angular, Ember.js, and React are additional frameworks that are worth exploring.

Recap

By focusing on file system modified events, these demos have tried to demonstrate server initiated updates.

With comparatively little code, web sites can be prepared to receive and apply unsolicited updates from the server. The granularity of the updates can be as little as a single string, can be a HTML fragment, or can be arbitrary data encoded in JSON.

Reserving web sockets for server initiated broadcast operations can keep your code small and understandable. Traditional HTTP GET and POST requests can be used for all client initiated retrieval and update operations.

This makes the division of labor between the client and server straightforward: the server is responsible for providing state -- both on demand and as the state changes. The client is responsible for updating the view to match the state.


You may see only a tiny bit of our escorts in Udaipur registered here on the website. You’ve got opportunity to select numerous all the more no matter the fact that you will have the capability to acquire the young girls of your fantasy all alone requirements.
Udaipur Call Girls
Goa Call girls
Nainital Escort service
Ramnagar Escort service
Haldwani Escort service
Rudrapur Escort service
Noida Call Girls
.Jodhpur Call Girls
Nainital Call Girls
Haldwani Call Girls
Ramnagar Call Girls
Rudrapur Call girls

Posted by Jennifer Kour at

Not all individual are blessed with such gift in writing and so is in developing and reading websites or programming codes. Some may have difficulties on composing their thoughts and expressing their ideas. Others were not taught well that’s why they do not know how to do it. Gladly many can have the benefit of available online platforms. Like https://www.bestessay.org/ they have a lot to offer.

Posted by Doyle Beltran at

5 Stars

Posted by parbrize auto ieftine at

awesome

Posted by offerzguru at

Click Here Chandigarh Escorts ??
Click Here Chandigarh Escort ??
Click Here Escorts In Chandigarh ??
Click Here Chandigarh Escorts Services ??
Click Here Chandigarh Independent Escorts ??
Click Here Chandigarh Independent Escort ??
Click Here Chandigarh Escort Service ??
Click Here Chandigarh Escorts Agency ??
Click Here Chandigarh Escort Agency ??
Click Here Chandigarh Call Girls ??
Click Here Chandigarh Call Girl ??

Posted by Dilpreet Kaur at

Are there any alternative services available apart from Web sockets for content updates! Seems to be web sockets are little slow while fetching fetching content from sources / destinations!~ Let me know! Thank you!

Posted by Call Girls in Hyderabad at

Poker88 asia— Ceme Keliling merupakan perkembangan dari permainan Ceme yang biasa dimainkan pada umumnya.

Permainan Ceme Keliling dikembangkan dari permainan Judi Ceme Online yang sudah ada sebelumnya, namun jika pada permaian Ceme online memiliki 1 dealer tetap pada setiap permainan, berbeda dengan Ceme Kililing ini karena yang menjadi dealernya itu para pemain yang berada didalam permaian tersebut dengan cara bergantian atau keliling berdasarkan arah jarum jam.

Posted by poker88 asia at

Thank you very much, you wrote a very good post, you have written this post through your thoughts and this post is really beautiful, such a post has seen very little till date and I am thankful that you have posted this very well Written.

Posted by riya kushik at

HOT CALL GIRLS IN JAIPUR | https://escortse.com/
Jaipur is a most beautiful and historical destination, for those who like to saw historical forts and palaces. https://escortse.com/ Now, this website is important for those want to spend time with Pink City escorts. This is a website for an [link] escorts agency that provides every kind of erotic service through different types of call girls. [link] You don’t find any average looking call girls in our agency in when you see our Hot escorts Jaipur then you defiantly say that we have most stunning call girls. So if you looking to take delight in Jaipur then come to us we give those kinds of high-class Foreigner escorts Jaipur for you who make your private party more exciting. [link] So on this holiday if you planning to come to Jaipur then don’t forget to take our Pink City escorts Service.
Escorts in Jaipur
Call Girls in jaipur
Escorts in bani park
VIP Call girls in jaipur
Escorts in jaipur
Call Girls in Jaipur

Posted by rena ravv at

Jaipur is a most beautiful and historical destination, for those who like to saw historical forts and palaces. https://escortse.com/ Now, this website is important for those want to spend time with Pink City escorts. This is a website for an http://vipmodel-escorts.com/ escorts agency that provides every kind of erotic service through different types of call girls. http://jaipurescorts.club/ You don’t find any average looking call girls in our agency in when you see our Hot escorts Jaipur then you defiantly say that we have most stunning call girls. So if you looking to take delight in Jaipur then come to us we give those kinds of high-class Foreigner escorts Jaipur for you who make your private party more exciting. http://jaipurescorts.club/ So on this holiday if you planning to come to Jaipur then don’t forget to take our Pink City escorts Service.
<a href="http://vipmodel-escorts.com/escort-service-in-sindhi-camp-jaipur/"> Escort Service in Sindhi Camp Jaipur</a>
<a href="http://vipmodel-escorts.com/escorts-in-banipark-jaipur/"> Escorts in bani park</a>
<a href="http://vipmodel-escorts.com/escorts-in-durgapura-jaipur/
"> Escorts in Durgapura Jaipur </a>
<a href="http://vipmodel-escorts.com/escorts-in-mansarovar-jaipur/"> Escorts in Mansarovar Jaipur</a>
<a href="http://vipmodel-escorts.com/"> Call Girls in Jaipur</a>
<a href="http://vipmodel-escorts.com/"> Jaipur Escorts Service</a>
<a href="http://vipmodel-escorts.com/kukas-escorts-jaipur-7665166866-model-call-girls-in-kukas/"> kukas Escorts Jaipur | Model call girls in kukas</a>
<a href="http://vipmodel-escorts.com/bhankrota-escorts-jaipur-7665166866-call-girls-bhankrota/">Bhankrota Escorts Jaipur | call girls bhankrota</a>
<a href="http://vipmodel-escorts.com/vaishali-nagar-escorts-7665166866-call-girls-vaishali-nagar/">vaishali nagar escorts call girls vaishali nagar</a>
<a href="http://vipmodel-escorts.com/call-girls-in-c-scheme-jaipur-7665166866-c-scheme-escorts/">call girls in c scheme jaipur | c scheme escorts</a>
<a href="http://vipmodel-escorts.com/sanganer-escorts-jaipur-7665166866-call-girls-sanganer/">sanganer escorts jaipur | call girls sanganer</a>
<a href="http://vipmodel-escorts.com/gopalpura-escorts-jaipur-7665166866-call-girls-gopalpura/">gopalpura escorts jaipur | call girls gopalpura</a>
<a href="http://vipmodel-escorts.com/bais-godam-escorts-jaipur-7665166866-call-girls-bais-godam/">bais godam escorts jaipur | call girls bais godam</a>
<a href="http://vipmodel-escorts.com/raja-park-escorts-jaipur-7665166866-call-girls-raja-park/">raja park escorts jaipur | call girls raja park</a>
<a href="http://vipmodel-escorts.com/malviya-nagar-escorts-jaipur-call-girls-7665166866/">malviya nagar escorts jaipur call girls</a>
<a href="http://vipmodel-escorts.com/vidhyadhar-nagar-escorts-jaipur-call-girls-7665166866/">vidhyadhar nagar escorts jaipur call girls</a>

Posted by rena ravv at

hi profile call girls in jodhpur & escort services
In this racing life we use to work every time but could not find the leisure time for our health, Yes you are right I’m just talking about health. The most important aspect of our life is to be happy and for this we do everything even marry. Here jodhpur Escorts is on running platform for unlimited entertainment call girls services in jodhpur. It is an awesome source of having fun in our life. We are across in jodhpur to serve our business for everybody. Our huge and pretty folk of fairies allure our intension and give us an unbeatable happiness. Our Call Girls Services are very affordable and easy to use 24 hours. We believe in happiness and loyalty from both sides. We use to do something different for Jodhpur Escorts entertainment. Some people want to get rid off from their wife and some wants to enjoy the entire life with a new connection search
https://jodhpurescortservices.com
https://jodhpurescortservices.com

Posted by Ms. Radhika Sexy at

If your life has stopped giving you pleasure due to some unknown reasons, than Sizzling Babes Escort Service & Call Girls in Jodhpur is the right place for you. It is still not too late to make it exciting. Tt is just we & with our wonderful buddies, we can make your life worth-living, if you spend a few moments with them. There is no such nudging in availing yourself of their companionship. What you need to is to just come to this city any time you like and get it touch with us VIP Escort Service In Jodhpur Being very warm and friendly, we will certainly respond to you positively and provide you the best services.

We are the best Call Girls service provider in Jodhpur Escort, We are in this industry from last 7 years. All our hot Jodhpur Call Girls are model, actress, Air Hostess and young Jodhpur Escort We cover all important areas in Jodhpur, So you can book your Jodhpur Call Girl by just dialing our number. Our service is Outstanding and We have lots of clients in Jodhpur who acquire this Service from us.

https://www.sizzlingbabes.com/
https://www.sizzlingbabes.com/

Posted by Ms. jodhpur escorts at

Poker88 asia— Bagi anda yang menyukai permainan judi kartu online tentunya sudah tidak asing lagi dengan permainan Super 10 ini, Terutama di Indonesia permaianan Super 10 ini sangat banyak digemari sekali oleh para pecinta judi kartu online.

Super 10 ini sangat lah mudah sekali dimainkan, oleh karena itu banyak sekali orang yang menyukai permainan Super 10. Permainan ini tidak mengenal umur, dari usia muda bahkan sampai orang tua menyukai permainan Super 10.

Posted by poker88 asia at

[link]
[link]
[link]
[link]
[link]
[link]
https://www.flea-market.net/user/profile/3664
[link]
[link]
[link]
https://kcentr.online/forum/index.php?topic=108052.0
[link]
https://www.pollexr.com/forum/index.php?topic=45042.0
[link]
[link]
https://www.playerclan.com/general/Escorts-in-Kolkata-call-girls-in-Kolkata-Kolkata-escorts-service-6344-new#new
https://finacialdiscussion.com/index.php?topic=24247.0
https://klubsistemasa.org/index.php?topic=8072.0
[link]
[link]
https://wikifintech.org/User:Kolkataqueens
[link]
https://physioexrx.com/index.php/User:Kolkataqueens
[link]
https://thesus.work/index.php?title=User:Kolkataqueens
https://coronawiki.five-stitches.net/mediawiki/index.php/User:Kolkataqueens
[link]
https://guineedebat.com/index.php?topic=112057.0
https://ourlibertydma.com/index.php?topic=64594.0
https://news.koinfinn.com/index.php?topic=114040.0
https://lbry.org/User_talk:Kolkataqueens
[link]
[link]
https://www.robotkaynagi.com/index.php?topic=10192.0
https://lost.trade/index.php?title=User_talk:Kolkataqueens
[link]
[link]
https://wiki.darkwind.org/index.php/User:Kolkataqueens
[link]
https://drawdownwiki.info/index.php/User:Kolkataqueens
[link]
https://elunivercity.net/wiki-startups/index.php/User:Kolkataqueens
https://rchesley.com/forum/index.php?topic=63711.0
[link]
https://konzertkalender-osnabrueck.de/oszillator-wiki/index.php?title=Benutzer:Kolkataqueens
https://8to80travel.org/index.php/User:Kolkataqueens
[link]
https://wiki.flo.cash/index.php/User:Kolkataqueens
[link]
[link]
[link]
https://geekpostware.com/Foro/index.php?topic=133734.0
https://whiteday.me/index.php/%E5%88%A9%E7%94%A8%E8%80%85:Kolkataqueens
https://www.carhubsales.com.au/jobs-business/business-for-sale/escorts-in-kolkata_i2196
https://taanschuurpolder.nl/index.php?topic=3488.0
https://forum.belso-osveny.hu/viewtopic.php?pid=95565#p95565
[link]
[link]
[link]
https://www.acheterlouer.xyz/multimedia/Consoles-et-Jeux-Video/kolkata-escorts-service_i61259
[link]
https://ufaclubth.com/boardweb/index.php?topic=8276.0
[link]
https://www.doe.go.th/prd/forum_bkk/1164537-kolkata-escorts-kolkata-escorts-service-escorts-in-kolkata
[link]
[link]
[link]
[link]
[link]
[link]
https://forum.kasumay-africa.com/index.php?topic=37719.0
[link]
[link]
[link]
[link]
[link]
https://realityodmajitelu.cz/user/profile/107975
https://coronawiki.net/index.php?title=Benutzer:Kolkataqueens
[link]
[link]
[link]
https://forum.m2.hk/home.php?mod=space&uid=51716
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
https://www.mynorcaljobs.com/employers/490509-kolkata-queens
https://jobs.soflophp.org/employers/490531-kolkata-queens
https://www.paksurf.com/kolkataqueens
https://fxjunction.com/profile/kolkataqueens
https://www.codingeek.com/forum/user/kolkataqueens
https://concussionlife.org/user/kolkataqueens/
[link]
[link]
[link]
https://www.wszgw.net/home.php?mod=space&uid=300543
[link]
[link]
https://www.toastandjamcommunity.com/community/general-discussions/how-do-i-solve-hp-test-fax-failure-problem
[link]
[link]
https://gforge.ictp.it/gf/user/kolkataqueens/userwiki/?&ref_id=2815&section=user&pageid=1743&feedback=Edited+ok
[link]
https://forum.paxcoin.co.kr/index.php?topic=154639.0
https://brasseka.com/index.php?topic=46443.0
[link]
https://concussionlife.org/forums/topic/kolkata-escortskolkata-escorts-serviceescorts-in-kolkata/
[link]
https://mauta.or.tz/forum/index.php?topic=5520.0
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
[link]
https://dancehalldatabase.com/user/view/user/queens01/uid/24701#!profile
https://cerberus-chain.be/member.php?action=profile&uid=15018
https://orcworm.co.uk/member.php?action=profile&uid=1369
https://www.mooc-web.fr/members/kolkataqueens/
https://www.wespeak.com/kolkataqueens
https://www.technercia.net/kolkataqueens
https://forum.saluofficial.com/user/kolkataqueens
https://forum.fastcap.com/profile/kolkataqueens/
[link]
[link]
https://taro-magic.ru/index.php?topic=77917.0
[link]
https://www.wespeak.com/read-blog/1890
https://www.technercia.net/read-blog/97
[link]
https://www.wpcgallup.org/forum/she-flies-on-discucssion/find-the-most-accurate-solution-as-you-find-hp-printer-not-printing-black
https://www.sportsboards.com/boards/idaho-hs-football/find-the-most-accurate-solution-as-you-find-hp-printer-not-printing-black
https://dancehalldatabase.com/forum/thread/threadid/5948
https://cerberus-chain.be/showthread.php?tid=4163
https://orcworm.co.uk/showthread.php?tid=26081

Posted by Kolkata escorts Service at

Reliable and Affordable Website Designing Company in Gurgaon who provides you Premium, Quality and Responsive Designs. We have experienced professionals who creates ultimate designs for your business. They are very dedicated about their work and having sound knowledge of all latest Technologies. They not build website only, they also develop a strong relationship between both. We provides many services like website designing, website development, seo services, ppc service, digital marketing, E-commerce development, software development and graphics designing. To know more about us just visit our website :- http://www.kartikwebtechnology.com

Posted by Web Design in Gurgaon at

best indica strains

cannabis oil cartridge

black jack strain
weed firm

globalnarcoticscenter.com

cannabis oil uses
runtz carts

pink runtz

runtz carts
Ace Of Spades

Dank vape Colorado

body relaxation
marijuana dispensary

buy cannabis online

cannabis oil cures cancer

Posted by dreammarketdarknet at

Thanks for sharing such a nice piece of information to us. This is very knowledgeable for me.

Posted by QuickBooks Online Login at

The best Surf Camp in Morocco. Fun and adventure in one of the best surf spots in the world

Posted by surf house at

Add your comment