zoukankan      html  css  js  c++  java
  • ng websocket

    ng使用websocket

    1.安装依赖库
    npm install ws --save

    2.安装类型定义文件

    npm install @types/ws --save

    3.编写服务

    import { Injectable } from '@angular/core';
    import {Observable} from "rxjs/Observable";

    @Injectable()
    export class WebSocketService {


    ws:WebSocket;

    constructor() { }

    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();
    }
    )
    }

    sendMessage(msg:string){
    this.ws.send(msg);
    }
    }

    4.在控制器中使用

    import { Component, OnInit } from '@angular/core';
    import {Observable} from "rxjs/Observable";
    import 'rxjs/add/operator/debounceTime';
    import 'rxjs/add/operator/throttleTime';
    import 'rxjs/add/observable/fromEvent';
    import 'rxjs/add/operator/retry';
    import {observable} from "rxjs/symbol/observable";
    import {HttpService} from "../service/http.service";
    import {WebSocketService} from "../service/web-socket.service";

    @Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {

    constructor(private httpreq:HttpService,private wsService:WebSocketService) {

    }


    ngOnInit() {
    //this.httpreq._get('',(data)=>console.log(data));
    this.wsService.createObservableSocket('ws://localhost:8080')
    .subscribe(
    data=>console.log(data),
    err=>console.log(err),
    ()=>console.log('it s over')
    )
    }

    sendMessageToServer(msg:string){
    this.wsService.sendMessage(msg);
    }


    }

  • 相关阅读:
    < high performance web sites > 阅读小记
    Gimp制作圆角透明图片
    iphone开发小记
    Android开发小记
    双网卡绑定(suse)
    xen虚拟机操作整理
    linux网络相关命令使用
    lua协程并发下载简单测试
    linux使用技巧(shell/vi/screen)
    爬虫之scrapy框架
  • 原文地址:https://www.cnblogs.com/norm/p/8023491.html
Copyright © 2011-2022 走看看