<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>websocket &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/websocket/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>Help you to find best ASP.NET Core Hosting</description>
	<lastBuildDate>Tue, 13 Dec 2022 04:38:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>websocket &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Use WebSocket to Push Real-Time Data to an Angular Service</title>
		<link>https://topreviewhostingasp.net/how-to-use-websocket-to-push-real-time-data-to-an-angular-service/</link>
					<comments>https://topreviewhostingasp.net/how-to-use-websocket-to-push-real-time-data-to-an-angular-service/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Tue, 13 Dec 2022 04:37:09 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular service]]></category>
		<category><![CDATA[angular tips]]></category>
		<category><![CDATA[websocket]]></category>
		<category><![CDATA[websocket tips]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3304</guid>

					<description><![CDATA[Pushing data from the server to the client is useful when applications need to display real-time data or when they want to leverage the speed and low-latency benefits provided by TCP/IP Web Socket connections. In this article tutorial, I will give how to demonstrate the process above. 1. Add Web Socket Functionality to the Server [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Pushing data from the server to the client is useful when applications need to display real-time data or when they want to leverage the speed and low-latency benefits provided by TCP/IP Web Socket connections.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="640" height="360" class="wp-image-862 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2017/11/angularjs.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2017/11/angularjs.png 640w, https://topreviewhostingasp.net/wp-content/uploads/2017/11/angularjs-300x169.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2017/11/angularjs-50x28.png 50w" sizes="(max-width: 640px) 100vw, 640px" /></figure></div>


<p>In this article tutorial, I will give how to demonstrate the process above.</p>



<p><strong>1. Add Web Socket Functionality to the Server</strong></p>



<p>There are a lot of options that can be used to add Web Socket functionality to the server – it really depends upon what language/framework you prefer. For the Angular/Web Socket example project, I went with Node.js and <a href="https://socket.io/" target="_blank" rel="noreferrer noopener">socket.io</a> since it’s easy to get up and running on any OS. The overall server is extremely easy to get up and running (keep in mind that I purposely kept it very basic to demonstrate the overall concept). The server starts a timer (used to simulate data changing on the server) once a client connection is made and returns data to one or more clients as the timer fires.</p>



<pre class="wp-block-code"><code>const express = require('express'),
      app = express(),
      server = require('http').createServer(app);
      io = require('socket.io')(server);

let timerId = null,
    sockets = new Set();

//This example emits to individual sockets (track by sockets Set above).
//Could also add sockets to a "room" as well using socket.join('roomId')
//https://socket.io/docs/server-api/#socket-join-room-callback

app.use(express.static(__dirname + '/dist')); 

io.on('connection', socket =&gt; {

  sockets.add(socket);
  console.log(`Socket ${socket.id} added`);

  if (!timerId) {
    startTimer();
  }

  socket.on('clientdata', data =&gt; {
    console.log(data);
  });

  socket.on('disconnect', () =&gt; {
    console.log(`Deleting socket: ${socket.id}`);
    sockets.delete(socket);
    console.log(`Remaining sockets: ${sockets.size}`);
  });

});

function startTimer() {
  //Simulate stock data received by the server that needs 
  //to be pushed to clients
  timerId = setInterval(() =&gt; {
    if (!sockets.size) {
      clearInterval(timerId);
      timerId = null;
      console.log(`Timer stopped`);
    }
    let value = ((Math.random() * 50) + 1).toFixed(2);
    //See comment above about using a "room" to emit to an entire
    //group of sockets if appropriate for your scenario
    //This example tracks each socket and emits to each one
    for (const s of sockets) {
      console.log(`Emitting value: ${value}`);
      s.emit('data', { data: value });
    }

  }, 2000);
}

server.listen(8080);
console.log('Visit http://localhost:8080 in your browser');</code></pre>



<p>The key part of the code is found in the <strong>io.on(‘connection’, …)</strong> section. This code handles adding client socket connections into a set, starts the timer when the first socket connection is made and handles removing a given socket from the set when a client disconnects. The <strong>startTimer()</strong> function simulates data changing on the server and handles iterating through sockets and pushing data back to connected clients (note that there are additional techniques that can be used to push data to multiple clients – see the included comments).</p>



<p>The next 3 steps all relate to the Angular service.</p>



<p>2. Create an Angular Service that Subscribes to the Data Stream Provided by the Server</p>



<p>3. Return an Observable from the Angular Service that a Component can Subscribe to</p>



<p>4. Emit data received in the Angular Service (from the service) to Observable subscribers</p>



<p>The Angular service subscribes to the data being pushed from the server using a script provided by socket.io (the script is defined in index.html). The service’s <strong>getQuotes()</strong> function first connects to the server using the <strong>io.connect()</strong> call. It then hooks the returned socket to “data” messages returned from the server. Finally, it returns an <strong>observable</strong> to the caller. The <strong>observable</strong> is created  by calling<strong> Observable.create()</strong> in the <strong>createObservable()</strong> function.</p>



<p>As Web Socket data is received in the Angular service, the observer object created in <strong>createObservable()</strong> is used to pass the data to any Angular subscribers by calling <strong>observer.next(res.data)</strong>. In essence, the Angular service simply forwards any data it receives to subscribers.</p>



<pre class="wp-block-code"><code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { map, catchError } from 'rxjs/operators';
import * as socketIo from 'socket.io-client';

import { Socket } from '../shared/interfaces';

declare var io : {
  connect(url: string): Socket;
};

@Injectable()
export class DataService {

  socket: Socket;
  observer: Observer;

  getQuotes() : Observable&lt;number&gt; {
    this.socket = socketIo('http://localhost:8080');

    this.socket.on('data', (res) =&gt; {
      this.observer.next(res.data);
    });

    return this.createObservable();
  }

  createObservable() : Observable&lt;number&gt; {
      return new Observable(observer =&gt; {
        this.observer = observer;
      });
  }

  private handleError(error) {
    console.error('server error:', error);
    if (error.error instanceof Error) {
        let errMessage = error.error.message;
        return Observable.throw(errMessage);
    }
    return Observable.throw(error || 'Socket.io server error');
  }

}</code></pre>



<p><strong>5. Subscribe to the Service Observable in a Component</strong></p>



<p>The final step involves a component subscribing to the observable returned from the service’s <strong>getQuotes()</strong> function. In the following code, <strong>DataService</strong> is injected into the component’s constructor and then used in the <strong>ngOnOnit()</strong> function to call <strong>getQuotes()</strong> and subscribe to the observable. Data that streams into the subscription is fed into a <strong>stockQuote</strong> property that is then rendered in the UI.</p>



<p>Note that the subscription object returned from calling <strong>subscribe()</strong> is captured in a <strong>sub</strong> property and used to unsubscribe from the <strong>observable</strong> when <strong>ngOnDestroy()</strong> is called.</p>



<pre class="wp-block-code"><code>import { Component, OnInit, OnDestroy } from '@angular/core';
import { DataService } from './core/data.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {

  stockQuote: number;
  sub: Subscription;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.sub = this.dataService.getQuotes()
        .subscribe(quote =&gt; {
          this.stockQuote = quote;
        });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}</code></pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Although this example is intentionally kept quite simple (there’s much more that could be added), it hopefully provides a nice starting point if you’re interested in streaming data to an Angular service using Web Sockets.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-use-websocket-to-push-real-time-data-to-an-angular-service/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
