SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
@yfain
WebSockets in Angular
Yakov Fain, Farata Systems



@yfain
About myself
• Work for Farata Systems
• Angular consulting and training
• Java Champion
• Co-authored two editions of the book

“Angular Development with TypeScript”
• email: yfain@faratasystems.com
Use the promo code fccfain 

for 37% off at manning.com
@yfain
What’s WebSocket protocol
• Low-overhead binary protocol
• Not a request/response based
• Supported by all modern browsers and servers
• Allows bidirectional message-oriented streaming of text
and binary data between browsers and web servers
@yfain
Where the server push is needed
• Live trading/auctions/sports notifications
• Controlling medical equipment over the web
• Chat applications
• Multiplayer online games
• Real-time updates in social streams
• Live charts
@yfain
@yfain
@yfain
WebSocket in a plain JavaScript client
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<span id="messageGoesHere"></span>
<script type=“text/javascript”>
var ws = new WebSocket("ws://localhost:8085");
ws.onmessage = function(event) {
var mySpan = document.getElementById("messageGoesHere");
mySpan.innerHTML=event.data;
};
ws.onerror = function(event){
ws.close();
console.log(`Error ${event}`);
}
</script>
</body>
</html>
simple-websocket-client.html
@yfain
Simple Node.js Websocket server
import * as express from "express";
import * as path from "path";
import {Server} from "ws";
const app = express();
// HTTP Server
app.get('/', (req, res) =>
res.sendFile(path.join(__dirname, '../simple-websocket-client.html')));
const httpServer = app.listen(8000, "localhost", () => {
const {port} = httpServer.address();
console.log(`HTTP server is listening on ${port}`);
});
// WebSocket Server
const wsServer = new Server({port:8085});
console.log('WebSocket server is listening on port 8085');
wsServer.on('connection',
wsClient => {
wsClient.send('This message was pushed by the WebSocket server');
wsClient.onerror = (error) =>
console.log(`The server received: ${error['code']}`);
}
);
simple-websocket-server.ts
@yfain
Upgrading the protocol
@yfain
Demo: Pushing to a JavaScript client
• Go to server dir
• tsc
• node build/simple-websocket-server
• Open the browser at http://localhost:8000
@yfain
Two ways of using WebSockets in Angular
1. Manually create an instance of the WebSocket object
2. Use RxJS WebSocketSubject
@yfain
Wrapping a WebSocket
object in a service
@yfain
WebSocket in Angular service
Think of WebSocket as a data producer for an Observable
stream
@yfain
export class WebSocketService{
ws: WebSocket;
socketIsOpen = 1; // WebSocket's open
createObservableSocket(url:string): Observable<any>{
this.ws = new WebSocket(url);
return new Observable(
observer => {
this.ws.onmessage = (event) => observer.next(event.data);
this.ws.onerror = (event) => observer.error(event);
this.ws.onclose = (event) => observer.complete();

// a callback invoked on unsubscribe()
return () => this.ws.close(1000, "The user disconnected");
}
);
}
sendMessage(message: string): string{
if (this.ws.readyState === this.socketIsOpen) {
this.ws.send(message);
return `Sent to server ${message}`;
} else {
return 'Message was not sent - the socket is closed';
}
}
}
Wrapping WebSocket in Angular service
websocket-service.ts
Emit data

from server
Send data

to server
@yfain
Using a WebSocket service in a component
export class AppComponent implements OnDestroy {
messageFromServer: string;
wsSubscription: Subscription;
status;
constructor(private wsService: WebSocketService) {
this.wsSubscription = this.wsService.createObservableSocket("ws://localhost:8085")
.subscribe(
data => this.messageFromServer = data, // Receiving
err => console.log( 'err'),
() => console.log( 'The observable stream is complete')
);
}
sendMessageToServer(){
this.status = this.wsService.sendMessage("Hello from client”); // Sending
}
closeSocket(){
this.wsSubscription.unsubscribe(); // Closing
this.status = 'The socket is closed';
}
ngOnDestroy() {
this.closeSocket();
}
}
websocket-service.ts
@yfain
Node server
import {Server} from "ws";
var wsServer = new Server({port:8085});
console.log('WebSocket server is listening on port 8085');
wsServer.on('connection',
websocket => {
websocket.send('Hello from the two-way WebSocket server');
websocket.onmessage = (message) =>
console.log('The server received:', message['data']);
websocket.onerror = (error) =>
console.log(`The server received: ${error['code']}`);
websocket.onclose = (why) =>
console.log(`The server received: ${why.code} ${why.reason}`);
}
);
two-way-websocket-server.ts
@yfain
Demo: Angular/Node send/receive
• Server: 

node build/two-way-websocket-server
• Client: 

ng serve --app wsservice
@yfain
Using RxJS
WebSocketSubject
@yfain
RxJS Subject
Rx.Subject is both an observable and observer
const mySubject = new Subject();
...
subscription1 = mySubject.subscribe(...);

subscription2 = mySubject.subscribe(...);

...

mySubject.next(123); // each subscriber gets 123
@yfain
RxJS WebSocketSubject
• A ready-to-use wrapper around the browser’s WebSocket
• Accepts either a string with the WebSocket endpoint or a
WebSocketSubjectConfig
• On subscribe, it uses either an existing connection or
creates a new one
• On unsubscribe, it closes connection if there are no other
subscribers
@yfain
When a server pushes data
• WebSocketSubject emits the data into observable
stream
• In case of a socket error, WebSocketSubject emits an
error
• If there are no subscribers, WebSocketSubject buffers
the value
@yfain
import { WebSocketSubject } from 'rxjs/observable/dom/WebSocketSubject';
...
export interface BidMessage {
productId: number;
price: number;
}
@Injectable()
export class BidService {
private _wsSubject: WebSocketSubject<any>;
private get wsSubject(): WebSocketSubject<any> {
const closed = !this._wsSubject || this._wsSubject.closed;
if (closed) {
this._wsSubject = WebSocketSubject.create(this.wsUrl);
}
return this._wsSubject;
}
get priceUpdates$(): Observable<BidMessage> {
return this.wsSubject.asObservable();
}
constructor(@Inject(WS_URL) private readonly wsUrl: string) {}
placeBid(productId: number, price: number): void {
this.wsSubject.next(JSON.stringify({ productId, price }));
}
}
BidService with WebSocketSubject
@yfain
Your
Angular 

Service
Component
WebSocket
Server

with STOMP

support



Browser
Integrating with server-side messaging
systems using STOMP protocol
StompService

from stomp.js
WebSocket Queue
Messaging
Server



Server
DI DI
STOMP docs: http://stomp.github.io/stomp-specification-1.2.html 



stomp.js: https://github.com/stomp-js/ng2-stompjs
@yfain
Online Auction

Architecture and code review
@yfain
The landing page of the Auction
HTTP

request
@yfain
Bids are pushed 

via WebSocket
The product detail page of the Auction
@yfain
Building blocks of ngAuction
@yfain
Demo of ngAuction
• Server (go to ng-auction/server dir):
• tsc
• node build/main
• Client (go to ng-auction/client)
• ng serve -o
@yfain
Thank you!
• Code samples:

https://bit.ly/2vhP35J
• Email: yfain@faratasystems.com
• Blog: yakovfain.com
• Twitter: @yfain


Contenu connexe

Tendances

The magic of flutter
The magic of flutterThe magic of flutter
The magic of flutterShady Selim
 
Introduction to cypress in Angular (Chinese)
Introduction to cypress in Angular (Chinese)Introduction to cypress in Angular (Chinese)
Introduction to cypress in Angular (Chinese)Hong Tat Yew
 
Introduction to Flutter
Introduction to FlutterIntroduction to Flutter
Introduction to FlutterApoorv Pandey
 
Introduction to Flutter - truly crossplatform, amazingly fast
Introduction to Flutter - truly crossplatform, amazingly fastIntroduction to Flutter - truly crossplatform, amazingly fast
Introduction to Flutter - truly crossplatform, amazingly fastBartosz Kosarzycki
 
Getting started with flutter
Getting started with flutterGetting started with flutter
Getting started with flutterrihannakedy
 
Flutter Tutorial For Beginners | Edureka
Flutter Tutorial For Beginners | EdurekaFlutter Tutorial For Beginners | Edureka
Flutter Tutorial For Beginners | EdurekaEdureka!
 
Mobile development with Flutter
Mobile development with FlutterMobile development with Flutter
Mobile development with FlutterAwok
 
Scheduling in Android
Scheduling in AndroidScheduling in Android
Scheduling in AndroidOpersys inc.
 
What is dotnet (.NET) ?
What is dotnet (.NET) ?What is dotnet (.NET) ?
What is dotnet (.NET) ?Talha Shahzad
 

Tendances (20)

Animations in Flutter
Animations in FlutterAnimations in Flutter
Animations in Flutter
 
CROSS PLATFORM APPLICATIONS DEVELOPMENT
CROSS PLATFORM APPLICATIONS DEVELOPMENT CROSS PLATFORM APPLICATIONS DEVELOPMENT
CROSS PLATFORM APPLICATIONS DEVELOPMENT
 
Flutter introduction
Flutter introductionFlutter introduction
Flutter introduction
 
The magic of flutter
The magic of flutterThe magic of flutter
The magic of flutter
 
Introduction to cypress in Angular (Chinese)
Introduction to cypress in Angular (Chinese)Introduction to cypress in Angular (Chinese)
Introduction to cypress in Angular (Chinese)
 
Java Security Framework's
Java Security Framework'sJava Security Framework's
Java Security Framework's
 
Introduction to Flutter
Introduction to FlutterIntroduction to Flutter
Introduction to Flutter
 
Wireshark - presentation
Wireshark - presentationWireshark - presentation
Wireshark - presentation
 
Introduction to Flutter - truly crossplatform, amazingly fast
Introduction to Flutter - truly crossplatform, amazingly fastIntroduction to Flutter - truly crossplatform, amazingly fast
Introduction to Flutter - truly crossplatform, amazingly fast
 
What is Flutter
What is FlutterWhat is Flutter
What is Flutter
 
Getting started with flutter
Getting started with flutterGetting started with flutter
Getting started with flutter
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Flutter workshop
Flutter workshopFlutter workshop
Flutter workshop
 
Flutter Tutorial For Beginners | Edureka
Flutter Tutorial For Beginners | EdurekaFlutter Tutorial For Beginners | Edureka
Flutter Tutorial For Beginners | Edureka
 
Flutter Intro
Flutter IntroFlutter Intro
Flutter Intro
 
Mobile development with Flutter
Mobile development with FlutterMobile development with Flutter
Mobile development with Flutter
 
Wireshark Basic Presentation
Wireshark Basic PresentationWireshark Basic Presentation
Wireshark Basic Presentation
 
WEB DEVELOPMENT USING REACT JS
 WEB DEVELOPMENT USING REACT JS WEB DEVELOPMENT USING REACT JS
WEB DEVELOPMENT USING REACT JS
 
Scheduling in Android
Scheduling in AndroidScheduling in Android
Scheduling in Android
 
What is dotnet (.NET) ?
What is dotnet (.NET) ?What is dotnet (.NET) ?
What is dotnet (.NET) ?
 

Similaire à Web sockets in Angular

WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersViktor Gamov
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web SocketsFahad Golra
 
vlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentationvlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets PresentationVolodymyr Lavrynovych
 
Server interaction with web socket protocol
Server interaction with web socket protocolServer interaction with web socket protocol
Server interaction with web socket protocolRahul Rai
 
Taming WebSocket with Scarlet
Taming WebSocket with ScarletTaming WebSocket with Scarlet
Taming WebSocket with ScarletZhixuan Lai
 
socket.io on SmartFx
socket.io on SmartFxsocket.io on SmartFx
socket.io on SmartFx剛志 森田
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxAbhijayKulshrestha1
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
Technologies That Make LINE QR Code Login Possible
Technologies That Make LINE QR Code Login PossibleTechnologies That Make LINE QR Code Login Possible
Technologies That Make LINE QR Code Login PossibleLINE Corporation
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)DK Lee
 
Wicket And Swing From One Codebase
Wicket And Swing From One CodebaseWicket And Swing From One Codebase
Wicket And Swing From One Codebasejcompagner
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkFabio Tiriticco
 

Similaire à Web sockets in Angular (20)

WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
 
Web-Socket
Web-SocketWeb-Socket
Web-Socket
 
Html5 websockets
Html5 websocketsHtml5 websockets
Html5 websockets
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
 
vlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentationvlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentation
 
Server interaction with web socket protocol
Server interaction with web socket protocolServer interaction with web socket protocol
Server interaction with web socket protocol
 
Taming WebSocket with Scarlet
Taming WebSocket with ScarletTaming WebSocket with Scarlet
Taming WebSocket with Scarlet
 
socket.io on SmartFx
socket.io on SmartFxsocket.io on SmartFx
socket.io on SmartFx
 
ITI006En-AJAX
ITI006En-AJAXITI006En-AJAX
ITI006En-AJAX
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptx
 
Real time coding with jWebSocket
Real time coding with jWebSocketReal time coding with jWebSocket
Real time coding with jWebSocket
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Technologies That Make LINE QR Code Login Possible
Technologies That Make LINE QR Code Login PossibleTechnologies That Make LINE QR Code Login Possible
Technologies That Make LINE QR Code Login Possible
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
 
Wicket And Swing From One Codebase
Wicket And Swing From One CodebaseWicket And Swing From One Codebase
Wicket And Swing From One Codebase
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
 
Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
 
ServerSentEventsV2.pdf
ServerSentEventsV2.pdfServerSentEventsV2.pdf
ServerSentEventsV2.pdf
 

Plus de Yakov Fain

Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Yakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsYakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsYakov Fain
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2Yakov Fain
 
Using JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsUsing JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsYakov Fain
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java DevelopersYakov Fain
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2Yakov Fain
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Yakov Fain
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developersYakov Fain
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in JavaYakov Fain
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java DevelopersYakov Fain
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov Fain
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTYakov Fain
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowYakov Fain
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptYakov Fain
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web ApplicationYakov Fain
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldYakov Fain
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual CompanyYakov Fain
 

Plus de Yakov Fain (20)

Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2
 
Using JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsUsing JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot apps
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoT
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business Workflow
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello World
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual Company
 

Dernier

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Dernier (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Web sockets in Angular

  • 1. @yfain WebSockets in Angular Yakov Fain, Farata Systems
 

  • 2. @yfain About myself • Work for Farata Systems • Angular consulting and training • Java Champion • Co-authored two editions of the book
 “Angular Development with TypeScript” • email: yfain@faratasystems.com Use the promo code fccfain 
 for 37% off at manning.com
  • 3. @yfain What’s WebSocket protocol • Low-overhead binary protocol • Not a request/response based • Supported by all modern browsers and servers • Allows bidirectional message-oriented streaming of text and binary data between browsers and web servers
  • 4. @yfain Where the server push is needed • Live trading/auctions/sports notifications • Controlling medical equipment over the web • Chat applications • Multiplayer online games • Real-time updates in social streams • Live charts
  • 7. @yfain WebSocket in a plain JavaScript client <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <span id="messageGoesHere"></span> <script type=“text/javascript”> var ws = new WebSocket("ws://localhost:8085"); ws.onmessage = function(event) { var mySpan = document.getElementById("messageGoesHere"); mySpan.innerHTML=event.data; }; ws.onerror = function(event){ ws.close(); console.log(`Error ${event}`); } </script> </body> </html> simple-websocket-client.html
  • 8. @yfain Simple Node.js Websocket server import * as express from "express"; import * as path from "path"; import {Server} from "ws"; const app = express(); // HTTP Server app.get('/', (req, res) => res.sendFile(path.join(__dirname, '../simple-websocket-client.html'))); const httpServer = app.listen(8000, "localhost", () => { const {port} = httpServer.address(); console.log(`HTTP server is listening on ${port}`); }); // WebSocket Server const wsServer = new Server({port:8085}); console.log('WebSocket server is listening on port 8085'); wsServer.on('connection', wsClient => { wsClient.send('This message was pushed by the WebSocket server'); wsClient.onerror = (error) => console.log(`The server received: ${error['code']}`); } ); simple-websocket-server.ts
  • 10. @yfain Demo: Pushing to a JavaScript client • Go to server dir • tsc • node build/simple-websocket-server • Open the browser at http://localhost:8000
  • 11. @yfain Two ways of using WebSockets in Angular 1. Manually create an instance of the WebSocket object 2. Use RxJS WebSocketSubject
  • 13. @yfain WebSocket in Angular service Think of WebSocket as a data producer for an Observable stream
  • 14. @yfain export class WebSocketService{ ws: WebSocket; socketIsOpen = 1; // WebSocket's open createObservableSocket(url:string): Observable<any>{ this.ws = new WebSocket(url); return new Observable( observer => { this.ws.onmessage = (event) => observer.next(event.data); this.ws.onerror = (event) => observer.error(event); this.ws.onclose = (event) => observer.complete();
 // a callback invoked on unsubscribe() return () => this.ws.close(1000, "The user disconnected"); } ); } sendMessage(message: string): string{ if (this.ws.readyState === this.socketIsOpen) { this.ws.send(message); return `Sent to server ${message}`; } else { return 'Message was not sent - the socket is closed'; } } } Wrapping WebSocket in Angular service websocket-service.ts Emit data
 from server Send data
 to server
  • 15. @yfain Using a WebSocket service in a component export class AppComponent implements OnDestroy { messageFromServer: string; wsSubscription: Subscription; status; constructor(private wsService: WebSocketService) { this.wsSubscription = this.wsService.createObservableSocket("ws://localhost:8085") .subscribe( data => this.messageFromServer = data, // Receiving err => console.log( 'err'), () => console.log( 'The observable stream is complete') ); } sendMessageToServer(){ this.status = this.wsService.sendMessage("Hello from client”); // Sending } closeSocket(){ this.wsSubscription.unsubscribe(); // Closing this.status = 'The socket is closed'; } ngOnDestroy() { this.closeSocket(); } } websocket-service.ts
  • 16. @yfain Node server import {Server} from "ws"; var wsServer = new Server({port:8085}); console.log('WebSocket server is listening on port 8085'); wsServer.on('connection', websocket => { websocket.send('Hello from the two-way WebSocket server'); websocket.onmessage = (message) => console.log('The server received:', message['data']); websocket.onerror = (error) => console.log(`The server received: ${error['code']}`); websocket.onclose = (why) => console.log(`The server received: ${why.code} ${why.reason}`); } ); two-way-websocket-server.ts
  • 17. @yfain Demo: Angular/Node send/receive • Server: 
 node build/two-way-websocket-server • Client: 
 ng serve --app wsservice
  • 19. @yfain RxJS Subject Rx.Subject is both an observable and observer const mySubject = new Subject(); ... subscription1 = mySubject.subscribe(...);
 subscription2 = mySubject.subscribe(...);
 ...
 mySubject.next(123); // each subscriber gets 123
  • 20. @yfain RxJS WebSocketSubject • A ready-to-use wrapper around the browser’s WebSocket • Accepts either a string with the WebSocket endpoint or a WebSocketSubjectConfig • On subscribe, it uses either an existing connection or creates a new one • On unsubscribe, it closes connection if there are no other subscribers
  • 21. @yfain When a server pushes data • WebSocketSubject emits the data into observable stream • In case of a socket error, WebSocketSubject emits an error • If there are no subscribers, WebSocketSubject buffers the value
  • 22. @yfain import { WebSocketSubject } from 'rxjs/observable/dom/WebSocketSubject'; ... export interface BidMessage { productId: number; price: number; } @Injectable() export class BidService { private _wsSubject: WebSocketSubject<any>; private get wsSubject(): WebSocketSubject<any> { const closed = !this._wsSubject || this._wsSubject.closed; if (closed) { this._wsSubject = WebSocketSubject.create(this.wsUrl); } return this._wsSubject; } get priceUpdates$(): Observable<BidMessage> { return this.wsSubject.asObservable(); } constructor(@Inject(WS_URL) private readonly wsUrl: string) {} placeBid(productId: number, price: number): void { this.wsSubject.next(JSON.stringify({ productId, price })); } } BidService with WebSocketSubject
  • 23. @yfain Your Angular 
 Service Component WebSocket Server
 with STOMP
 support
 
 Browser Integrating with server-side messaging systems using STOMP protocol StompService
 from stomp.js WebSocket Queue Messaging Server
 
 Server DI DI STOMP docs: http://stomp.github.io/stomp-specification-1.2.html 
 
 stomp.js: https://github.com/stomp-js/ng2-stompjs
  • 25. @yfain The landing page of the Auction HTTP
 request
  • 26. @yfain Bids are pushed 
 via WebSocket The product detail page of the Auction
  • 28. @yfain Demo of ngAuction • Server (go to ng-auction/server dir): • tsc • node build/main • Client (go to ng-auction/client) • ng serve -o
  • 29. @yfain Thank you! • Code samples:
 https://bit.ly/2vhP35J • Email: yfain@faratasystems.com • Blog: yakovfain.com • Twitter: @yfain