Angular web socket服务小例子报错

0 0 angular4
墙扶不起的阿斗
墙扶不起的阿斗

声望值:106 0人

2019-01-11 15:53:35 提问

关注 0关注

收藏 0收藏, 115浏览

整体上就是一个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 {
     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");
  }
}
请先 登录 后评论

1个回答

注册新账号

悬赏追问
10
  • 10
  • 20
  • 50
  • 100
  • 200
  • 输入数值
发布追问