【问题标题】:Using web socket in angular 6在角度 6 中使用网络套接字
【发布时间】:2019-03-28 07:25:45
【问题描述】:

我正在尝试从网络套接字获取数据。我正在将 websocket 对象初始化为全局对象。

socket =new WebSocket('ws://xx.xx.xx.xx:xxxx/socket');

在 ngOnInit 上,我正在打开连接:

this.socket.onopen = function(){
    console.log("websocket is open now");
  }

现在我需要使用从 UI 触发的函数发送消息,并且来自 websocket 的回复应该将消息存储在全局变量中。

sampleFunction(val) {
    this.socket.send(val);
    this.socket.onmessage=function(event){
      console.log("got message");
      this.dummy=event.data;
    }.bind(this)
  }

所以在页面加载时它正在连接,但是当我触发该功能时,消息没有发送,因此我没有收到任何回复

【问题讨论】:

  • 你有什么问题?
  • "global" = 角度服务

标签: angular websocket angular6


【解决方案1】:

我正在使用 Angular 自带的 rxjs 及其 webSocket 方法。

import {webSocket} from 'rxjs/webSocket';
socket = webSocket(`${environment.serviceWebSockets}/api`);
constructor(){
    // now you can subscribe to messages wherever in your code
    this.socket.subscribe(message => {
        console.log(message); // or just use it directly
    }, error => {
        console.error(error); // handle errors
    });
}

通过这个 webSocket 发送数据:

socket.next(JSON.stringify({some:"data"}));

连接使用:

socket.subscribe();

断开连接:

socket.complete();

更多信息https://rxjs-dev.firebaseapp.com/api/webSocket/webSocket

【讨论】:

  • 您能分享一下实施文档吗?这将显示如何打开连接,然后将一些数据发送到 ws 服务器。
  • 在哪里打开和关闭连接?消息变量是什么?
  • 您不需要消息和错误变量,我修复了帖子,您只需在订阅中收到消息和错误变量时处理它们。当服务器发送某些内容时,您会收到消息,然后您会使用下一个发送到服务器。
  • 我面临的另一个问题是,我正在向 websocket 发送一个变量,但如果接收到它的值是用双引号引起的,因此我无法在 websocket 服务器端运行一些逻辑。
  • 您可能必须解析数据,使用 JSON.parse 或尝试发送普通对象
【解决方案2】:

实际上在 AngularCli 应用程序中,您可以定义这样的服务并开始连接到 Web 套接字服务器

 // websocket.servoce.ts
 import { Injectable } from "@angular/core";
 import { webSocket } from "rxjs/webSocket";


 @Injectable()
 export class WebsocketService {

   // ha ha look at the host address
   private subject = webSocket("ws://xxx.xxx.xxx.xxx:xxxx ;)/ws/");
   // use pipe to push data into components
   constructor() {
     console.log("websocket service initialization");
   }

   subscribe() {
     this.subject.subscribe(
       msg => {
         console.log(msg);
         // use angular data pipe to push data into components that is subscribed on pipe
       },
       err => {
         console.log(err);
       }
      )
   }

 }

感谢您使用此服务

【讨论】:

    【解决方案3】:

    我相信 RxJs 套接字期望有效负载是有效的 json,您是在发送字符串还是?

    【讨论】:

    • 我正在发送一个字符串,但在服务器端正在正确获取数据并正确处理它并发送浏览器的响应。唯一的问题是响应没有被消息变量捕获;
    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 2016-04-07
    • 2018-03-11
    • 2012-09-29
    相关资源
    最近更新 更多