本文介绍了在angular2 webapp项目中使用sockjs-client/sockjs创建Websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Angular2 webapp项目用于FRONT-END,将Vertex3用于BACK-END.

I'm using Angular2 webapp project for FRONT-END and Vertex3 for BACK-END.

使用Sockjs客户端,我正在创建websocket(在客户端),以在前端和后端之间创建通信通道.

Using Sockjs-client i'm creating websocket (at client side) to create a communication channel between Frontend and Backend.

我已经使用npm安装了sockjs-client:

I have installed sockjs-client using npm :

当我在LoginService.ts文件中导入sockjs-client时:

When I import sockjs-client in LoginService.ts file :

export class LoginService {
URL: string = 'http://localhost:8082/eventbus';
sock: SockJS;
handlers = {};

private _opened: boolean = false;

public open(): void {
    if (!this._opened) {
        this.sock = new SockJS(this.URL);
    this.sock.onopen = (e) => {
            this.callHandlers('open', e);
        }
        this.sock.onmessage = (e) => {
            this.messageReceived(e);
        }
        this.sock.onclose = (e) => {
            this.callHandlers('close', e);
        }
        this._opened = true;
    }

    public isOpen(): boolean {
    return this._opened;
}

public close(): void {
    if (this._opened) {
        this.sock.close();
        delete this.sock;
        this._opened = false;
    }
}

private messageReceived (e) {
    var msg = JSON.parse(e.data);
    this.callHandlers('message', msg.type, msg.originator, msg.data);
}

private callHandlers (type: string, ...params: any[]) {
    if (this.handlers[type]) {
        this.handlers[type].forEach(function(cb) {
            cb.apply(cb, params);
        });
    }
}
public send (type: string, data: any) {
    if (this._opened) {
        var msg = JSON.stringify({
            type: type,
            data: data
        });

        this.sock.send(msg);
    }
}


}

使用

但是在客户端没有创建websocket连接.因为我已经使用顶点vertex.createHttpServer创建了服务器(该宿主位于: http://localhost:8082 ).

But no websocket connection is created at client side. As I have already created server using vertex vertex.createHttpServer ( which is hosted on : http://localhost:8082).

所以我有两个问题:

1.无法在angular2 webapp中导入sockjs-client,因此无法创建websocket连接.

1.Unable to import sockjs-client in angular2 webapp , so can't create websocket connection.

2.在node_modules中找不到以angular2 webapp项目作为"sockjs-client"的错误(奇怪的是它存在于node_modules中)

2.Error while building an angular2 webapp project as 'sockjs-client' is not found in node_modules (weird is that its present in node_modules )

有什么我想念的吗?

预先感谢!!!

推荐答案

找到了一种在不使用typings的情况下将sockjs集成到angular2中的方法.

Found a way to integrate sockjs in angular2 without using typings.

使用以下步骤:

  1. index.html
  2. 中导入sockjs-event.jssockjs-client.js
     <!doctype html>
     <html>
      <head>
      <meta charset="utf-8">
        <title>MyApp</title>
        <script src="/sockjs-client.js"></script>
        <script src="/sockjs-event.js"> </script>

         ......
         </head>
         <body>
          <my-app>Loading...</my-app>
        </body>
     </html>
  1. 创建导出服务myapp.service.ts
  1. Create an export Service myapp.service.ts
    declare var EventBus: any;
    @Injectable()
     export class ConsoleService {
      URL: string = 'http://localhost:8082/eventbus';
      handlers = {};
      eventBus: any;
      private _opened: boolean = false;

       public open(): void {

       if (!this._opened) {
        this.eventBus = new EventBus(this.URL);
        this.eventBus.onopen = (e) => {
               this._opened = true;
                console.log("open connection");
                this.callHandlers('open', e);
                this.eventBus.publish("http://localhost:8082", "USER LOGIN                 INFO");

                this.eventBus.registerHandler("http://localhost:8081/pushNotification", function (error, message) {
                   console.log(message.body);


                //$("<div title='Basic dialog'>Test   message</div>").dialog();

          });
        }
        this.eventBus.onclose = (e) => {
            this.callHandlers('close', e);
          }
        }
    }

     public isOpen(): boolean {
      return this._opened;
     }

    public close(): void {
      if (this._opened) {
        this.eventBus.close();
        delete this.eventBus;
        this._opened = false;
     }

     }

      .......



    public send (type: string, data: any) {
        if (this._opened) {
            var msg = JSON.stringify({
              type: type,
             data: data
          });

          this.eventBus.publish("http://localhost:8082",msg);
        }
      }
    };

     export default ConsoleService;
  1. 在我的情况下转到您的启动模块app.module.ts并在角度引导程序中加载服务myapp.service.ts
  1. Go to your starting module in my case it is app.module.ts and load your service myapp.service.ts in angular bootstrap
      import { AppComponent } from './app.component';
      ....
      import { ConsoleService } from 'services/myapp.service';

        @NgModule({
          imports: [
            ....
          ],
        providers:    [ ConsoleService ],

      declarations: [
          AppComponent,
        ...
       ],
         bootstrap: [AppComponent]
     })
      import { Component } from '@angular/core';
      import 'style/app.scss';
      import { ConsoleService } from 'services/globalConsole.service';
      @Component({
       selector: 'my-app', // <my-app></my-app>
       templateUrl: './app.component.html',
       styleUrls: ['./app.component.scss']

      })

    export class AppComponent {

      constructor (private consoleService: ConsoleService) {
        consoleService.onOpen((e) => {
                 consoleService.send('message', "xyz");
             });

          consoleService.open();
       }

  }
  1. 最后,您可以使用import ConsoleService在任何.ts文件中使用EventBuspublishregisterHandler.
  1. Finally you can use EventBus to publish and registerHandler in any .ts file using import ConsoleService .

我希望这会有所帮助:)

这篇关于在angular2 webapp项目中使用sockjs-client/sockjs创建Websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-09 14:48