最后一個了 websocket,我還沒有在項目中使用過webscoket —— 馬丁路德.東
1.我們之前做過一個websocket的服務(在根模塊的providers中聲明他)
import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable";
import 'rxjs/RX';
@Injectable()
export class WebSocketService {
ws:WebSocket;
constructor() { }
createObserverbleSocket(url:string,id:number): Observable<any> {
this.ws = new WebSocket(url);
return new Observable<string>(
observer => {
//接受到消息
this.ws.onmessage = (event) => observer.next(event.data);
//ws出錯
this.ws.onerror = (event) => observer.error(event);
//ws打開時
this.ws.onopen = (event) => this.sendMessage({productId:id});
//ws流關閉
this.ws.onclose = (event) => observer.complete();
//如果取消關注,就斷開ws
return () => this.ws.close();
).map(message => {
console.log(message);
return JSON.parse(message);
});;
}
//服務器主動發送消息
sendMessage(message:any){
this.ws.send(JSON.stringify(message));
}
}
2.在商品詳情的控制器里注入服務(在構造函數中哦)
在HTMl上有一些綁定的數據
<div class="thumbnail">
<button class="btn btn-default btn-lg"[class.active]="isWatched"
(click)="watchProduct()" >
{{isWatched?'取消關注':'關注'}}
</button>
<label>最新出價{{currentBid | number: '.2-2'}}元</label>
</div>
1.控制器里(建立ws連接,發送請求)
!只能發字符串哦
this.subscription = this.wsServer.createObserverbleSocket('ws://localhost:8085',this.product.id)
找到自己所要的價格做一次查詢
this.subscription = this.wsServer.createObserverbleSocket('ws://localhost:8085',this.product.id)
.subscribe(
products => {
let product = products.find(p => p.productId === this.product.id)
this.currentBid = product.bid;
console.log(product.bid);
}
);
3.服務器端代碼,
const subscription = new Map<any,number[]>();
const wsServer = new Server({port:8085});
wsServer.on("connection",websocket => {
// websocket.send("消息為服務器主動發送");
websocket.on("message",messsge => {
//字符串轉化為json
let messageObj = JSON.parse(messsge);
//取出客戶端之前訂閱的商品
let productIds = subscription.get(websocket) || [];
//將數據一起放在集合中
subscription.set(websocket,[...productIds,messageObj.productId]);
})
});
3.1服務器發送請求
const currenBids = new Map<number,number>();
setInterval(() => {
products.forEach( p => {
//獲取最新價格,不然就取原價格。
let currenBid = currenBids.get(p.id) || p.price;
//生成最新的價格
let newBid = currenBid + Math.random() * 5;
//將新價格放入集合
currenBids.set(p.id, newBid);
});
subscription.forEach((productIds:number[], ws) =>{
//判斷是否連接
if(ws.readyState === 1){
//將所需要的數據,整理為對象
let newBides = productIds.map( pid => ({
productId:pid,
bid:currenBids.get(pid)
}));
//轉化為字符串,發送出去。
ws.send(JSON.stringify(newBides));
}else{
//如果沒有連接,就從數組中刪除
subscription.delete(ws);
}
})
},2000)
4.取消關注(流會返回一個的對象,我們以此判斷是否關注)
屬性就是
subscription:Subscription;
訂閱是去承接對象
this.subscription = this.wsServer.createObserverbleSocket('ws://localhost:8085',this.product.id)
.subscribe(
products => {
let product = products.find(p => p.productId === this.product.id)
this.currentBid = product.bid;
console.log(product.bid);
}
);
根據是否訂閱來執行相應的操作。
if(this.subscription ){
//取消訂閱
this.subscription.unsubscribe();
this.isWatched = false;
this.subscription = null;
}else{
this.isWatched = true;
this.subscription = this.wsServer.createObserverbleSocket('ws://localhost:8085',this.product.id)
.subscribe(
products => {
let product = products.find(p => p.productId === this.product.id)
this.currentBid = product.bid;
console.log(product.bid);
}
);
}