简体   繁体   English

Angular 1.5:多个WebSocket连接

[英]Angular 1.5: multiple WebSocket connections

I'm trying to create a service or factory using Angular 1.5 (with ES6) where I could have multiple instances of it, each one having a different connection to a WebSocket (the main purpose of this is a chat system). 我正在尝试使用Angular 1.5(带有ES6)创建服务或工厂,在该服务或工厂中我可以拥有多个实例,每个实例与WebSocket的连接都不同(其主要目的是聊天系统)。

I was able to do a service that works for a single WebSocket connection, but given the purpose of this project, I need to be able to connect to different "rooms" but each one of them has a URL with different connection parameters (like so: ws://localhost:8080/chat/<param1>/<param2> ). 我能够为单个WebSocket连接提供服务,但是鉴于该项目的目的,我需要能够连接到不同的“房间”,但是每个房间都有一个带有不同连接参数的URL(例如, : ws://localhost:8080/chat/<param1>/<param2> )。

I'm using angular-websocket ( https://github.com/AngularClass/angular-websocket ). 我正在使用angular-websockethttps://github.com/AngularClass/angular-websocket )。 Since I'm using ES6 with strict mode, I have to inject $websocket from this lib and create immediately an instance of it on the constructor. 由于我在严格模式下使用ES6,因此必须从此lib中注入$websocket并立即在构造函数上创建其实例。

So, what I'm looking for is: being able to create multiple WebSocket connections, ideally in a service/factory, where each one of them has its own connection parameters (which would be given on the controller where this service will be instantiated), and then each instance would be able to manage the sending/receiving of new respective "room" messages. 因此,我要寻找的是:能够创建多个WebSocket连接,理想情况下是在服务/工厂中,其中每个连接都有自己的连接参数(将在实例化此服务的控制器上给出) ,然后每个实例将能够管理新的相应“房间”消息的发送/接收。

Using ES5, I could probably create a non-singleton service or factory and that could probably solve this problem, but as I'm learning ES6 I would really love to have this solved that way. 使用ES5,我可能可以创建一个非单一服务或工厂,这可能可以解决此问题,但是当我学习ES6时,我真的很想以这种方式解决这个问题。 Here's my current Chat service class, which currently only is able to handle a static connection, and it's a singleton. 这是我当前的Chat服务类,该类目前仅能够处理静态连接,并且是单例。

export default class ChatService {
  constructor($websocket) {
    'ngInject';

    this._$websocket = $websocket('wss://localhost:8080/chat' + '/param1/param2');
    this.collection = [];

    this.init();
  }

  init() {
    this._$websocket.onMessage(this.onMessage);
    this._$websocket.onOpen(this.onOpen);
    this._$websocket.onClose(this.onClose);
    this._$websocket.onError(this.onError);
  }

  onOpen() {
    console.log('Connection open');
  }

  onClose(event) {
    console.log('Connection closed: ', event);
  }

  onError(event) {
    console.log('Connection Error: ', event);
  }

  onMessage(message) {
    this.collection.push(JSON.parse(message.data));
  }

  closeSocket() {
    this._$websocket.close();
  }

  sendMessage(text) {
    // Code to send a message using this connection
  }
}

If you have any other suggestion on how to tackle this problem, I'm all ears. 如果您对如何解决此问题还有其他建议,我非常高兴。

Thank you. 谢谢。

I use jquery atmosphere js for multi socket connection. 我使用jquery大气js进行多套接字连接。 You can use it. 您可以使用它。

Exapmle multi connection code : 示例多连接代码:

HTML HTML

<button id="b1">
ping s1
</button>

<button id="b2">
ping s1
</button>

<div id="s1">
  <h1>s1 pings</h1>  
  <p></p>
</div>


<div id="s2">
  <h1>s2 pings</h1>
  <p></p>
</div>

JS: JS:

var container;
function Request(sU) {
    this.url = sU;
    this.contentType = 'application/json';
    this.logLevel = 'debug';
    this.trackMessageLength = false;
    this.enableProtocol = false;
    this.enableXDR = true;
    this.transport = 'websocket';
    this.fallbackTransport = 'sse';
    this.reconnectInterval = 5000;
    this.connectTimeout = 30000;
    this.timeout = 60000;
    this.maxReconnectOnClose = 3;
    this.isDetail = false;
    this.suspend = true;
    //this.headers           = {device: $rootScope.imageType}
    this.onOpen = function(response) {
        console.log("connected");
    };

    this.onReopen = function(response) {};

    this.onMessage = function(response) {
        $(container).append("<br>" + response.responseBody );
        console.log(response)
    };

    this.onClientTimeout = function(request) {};


    this.onReconnect = function(request, response) {};

    this.onError = function(response) {};

    this.onClose = function(response) {};
};// Request

function SocketConnector(sU) {
    return {
        request: new Request(sU),
        socket: null,
        closeSocket: function(aciklama) {
            this.socket.close();
        }, //closeSocket
        connectSocket: function() {
                this.socket = $.atmosphere.subscribe(this.request);
            } //connectSocket
    };
};


var socket1  = new SocketConnector('https://echo.websocket.org');
socket1.connectSocket();
$("#b1").click(function(){
  container = "#s1";
    socket1.socket.push(Date.now())
});
var socket2  = new SocketConnector('https://echo.websocket.org');
socket2.connectSocket();
$("#b2").click(function(){
  container = "#s2";
    socket2.socket.push(Date.now())
});

You can write this in any angular service js. 您可以在任何角度服务js中编写此代码。

Look at JS Fiddle example . JS Fiddle示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM