Angular web socket服务小例子报错

拾光过客
  • 605

整体上就是一个web socket服务小例子。报错信息如下:
这是啥原因呢?

component.ts

export class WebSocketComponent implements OnInit {
  constructor(private wsService: WebSocketService) { }
  ngOnInit() {
    this.wsService.createObservableSocket("ws://localhost:8085").subscribe(
      data => console.log(data),
      err => console.log(err),
      () => console.log("流已经结束")
    );
  }
  sendMessageToServer() {
    this.wsService.sendMessage("Hello from client");
  }
}

浏览器定位:(service.ts)
图片描述

控制台输出:
图片描述

====================================================
完整代码如下:
1.服务器端:

import {Server} from 'ws';
const wsServer = new Server({port:8085});
wsServer.on("connection", websocket => {
    websocket.send("这个消息是服务器主动推送的!");
    websocket.on("message", message => {
        console.log("接收到消息:" + message)
    })
})

2.客户端Serves:

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(message: string) {
     this.ws.send(message);
   }
}

3.客户端控制器TS:

export class WebSocketComponent implements OnInit {

  constructor(private wsService: WebSocketService) { }
  ngOnInit() {
    this.wsService.createObservableSocket("ws://localhost:8085").subscribe(
      data => console.log(data),
      err => console.log(err),
      () => console.log("流已经结束")
    );
  }
  sendMessageToServer() {
    this.wsService.sendMessage("Hello from client");
  }
}
回复
阅读 2k
1 个回答

服务器启动了么

宣传栏