SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
@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


Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5Gil Fink
 
OWASP Poland Day 2018 - Frans Rosen - Attacking modern web technologies
OWASP Poland Day 2018 - Frans Rosen - Attacking modern web technologiesOWASP Poland Day 2018 - Frans Rosen - Attacking modern web technologies
OWASP Poland Day 2018 - Frans Rosen - Attacking modern web technologiesOWASP
 
Chapter 1 Getting Started with HTML5
Chapter 1 Getting Started with HTML5Chapter 1 Getting Started with HTML5
Chapter 1 Getting Started with HTML5Dr. Ahmed Al Zaidy
 
World wide web An Introduction
World wide web An IntroductionWorld wide web An Introduction
World wide web An IntroductionSidrah Noor
 
Windows Attacks AT is the new black
Windows Attacks   AT is the new blackWindows Attacks   AT is the new black
Windows Attacks AT is the new blackRob Fuller
 
Lecture 1 intro to web designing
Lecture 1  intro to web designingLecture 1  intro to web designing
Lecture 1 intro to web designingpalhaftab
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validationMaitree Patel
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
Introduction to web technology
Introduction to web technologyIntroduction to web technology
Introduction to web technologyVARSHAKUMARI49
 
HTML5 introduction for beginners
HTML5 introduction for beginnersHTML5 introduction for beginners
HTML5 introduction for beginnersVineeth N Krishnan
 

Was ist angesagt? (20)

GET and POST in PHP
GET and POST in PHPGET and POST in PHP
GET and POST in PHP
 
History of-web-design
History of-web-designHistory of-web-design
History of-web-design
 
Blind XSS & Click Jacking
Blind XSS & Click JackingBlind XSS & Click Jacking
Blind XSS & Click Jacking
 
Javascript
JavascriptJavascript
Javascript
 
Secure PHP Coding
Secure PHP CodingSecure PHP Coding
Secure PHP Coding
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
OWASP Poland Day 2018 - Frans Rosen - Attacking modern web technologies
OWASP Poland Day 2018 - Frans Rosen - Attacking modern web technologiesOWASP Poland Day 2018 - Frans Rosen - Attacking modern web technologies
OWASP Poland Day 2018 - Frans Rosen - Attacking modern web technologies
 
Js ppt
Js pptJs ppt
Js ppt
 
Chapter 1 Getting Started with HTML5
Chapter 1 Getting Started with HTML5Chapter 1 Getting Started with HTML5
Chapter 1 Getting Started with HTML5
 
Web Application
Web ApplicationWeb Application
Web Application
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
XSS - Attacks & Defense
XSS - Attacks & DefenseXSS - Attacks & Defense
XSS - Attacks & Defense
 
World wide web An Introduction
World wide web An IntroductionWorld wide web An Introduction
World wide web An Introduction
 
Windows Attacks AT is the new black
Windows Attacks   AT is the new blackWindows Attacks   AT is the new black
Windows Attacks AT is the new black
 
Lecture 1 intro to web designing
Lecture 1  intro to web designingLecture 1  intro to web designing
Lecture 1 intro to web designing
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Introduction to web technology
Introduction to web technologyIntroduction to web technology
Introduction to web technology
 
HTML5 introduction for beginners
HTML5 introduction for beginnersHTML5 introduction for beginners
HTML5 introduction for beginners
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 

Kürzlich hochgeladen (20)

IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 

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