在构建时未知地址时如何确定服务器WebSocket URL?

时间:2019-05-24 12:17:12

标签: angular websocket server

尽管我对Web套接字比较陌生,但我的开发环境的Angular-7客户端和node / express开发服务器正在使用WebSockets进行通信非常成功。

问题在于,在部署中,实际的服务器将在便携式仪器上运行,该仪器本身可以位于 any 客户网络上的 any 手动IP地址。 / p>

有许多将Angular与WebSockets结合使用的示例。它们都使用已知的IP地址。我正在学习的技术非常简单。基本的WebSocket创建代码如下所示:

websocket.service.ts

 constructor() {
    this.socket$ = new WebSocketSubject(environment.wsUrl);
    this.subscription$ = this.socket$
      .subscribe(
      (message) => this.processWebSocketMessage(message),
      (err) => console.error(err),
      () => console.warn('Connection closed')
    );
  }

environment.ts

export const environment = {
  production: false,
  wsUrl: 'ws://localhost:8999'
};

我的问题是,我没有找到有关其IP服务器的生产版本( environment.prod.ts )的 wsUrl 属性值应该是什么的示例。地址在构建时未知。

我强烈怀疑我在这里遗漏了一些非常简单的东西。我应该动态确定服务器IP地址吗?欢迎所有建议。

2 个答案:

答案 0 :(得分:0)

在environment.ts中没有wsUrl。您可以通过服务获取url,然后创建您的websocket套接字。

websocket.service.ts

constructor(private servUrl:UrlService) {

servUrl.getUrlDinamicaly().subscribe(res => {

    this.socket$ = new WebSocketSubject(res.wsUrl);

    this.subscription$ = this.socket$.subscribe(
      (message) => this.processWebSocketMessage(message),
      (err) => console.error(err),
      () => console.warn('Connection closed')
    );
  }
 );
}

url-service.service.ts

  getUrlDinamicaly(){
    return this.httpClient.get(this.serverUrl + '/get_url_server');
  }

使用 getUrlDinamicaly ,您将获得WebSocket服务器的当前URL。服务服务器无法更改其网址。

答案 1 :(得分:0)

针对多种浏览器进行更深入的研究和测试。我已经确定了以下解决方案。浏览器已经“知道”服务器的地址。唯一的附加部分是根据当前环境提供正确的端口。

websocket.service.ts

   this.socket$ = new WebSocketSubject(
     'ws://' + window.location.hostname + ':' + environment.wsPort
   );

environment.ts

export const environment = {
  production: false,
  wsPort: 8999
};

environment.prod.ts

export const environment = {
  production: true,
  wsPort: 8080
};