最后一个了 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);
}
);
}