代码之家  ›  专栏  ›  技术社区  ›  Shasha

在angular2 webapp项目中使用sockjs client/SockJSs创建Websocket

  •  1
  • Shasha  · 技术社区  · 9 年前

    我使用Angular2 webapp项目作为前端,使用Vertex3作为后端。

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

    我已经使用npm安装了sockjs客户端:

    npm安装sockjs客户端

    当我在LoginService中导入sockjs客户端时。ts文件:

    从“SockJS客户端”导入*作为SockJS;

    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);
        }
    }
    
    
    }
    

    使用运行angular2 webapp项目时没有错误

    npm运行服务器

    但在客户端不创建websocket连接。因为我已经使用vertex创建了服务器 vertex.createHttpServer (托管于: http://localhost:8082 ).

    所以我有两个问题:

    1.无法在angular2 webapp中导入sockjs客户端,因此无法创建websocket连接。

    我还缺什么吗?

    提前感谢!!!

    1 回复  |  直到 9 年前
        1
  •  1
  •   Shasha    9 年前

    找到了一种在angular2中集成sockjs的方法,无需使用 typings .

    使用以下步骤:

    1. 进口 sockjs-event.js 和 sockjs-client.js 在里面 index.html
         <!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
        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 并加载您的服务
          import { AppComponent } from './app.component';
          ....
          import { ConsoleService } from 'services/myapp.service';
    
            @NgModule({
              imports: [
                ....
              ],
            providers:    [ ConsoleService ],
    
          declarations: [
              AppComponent,
            ...
           ],
             bootstrap: [AppComponent]
         })
    

    4.从启动组件调用OpenWebSocket app.component.ts

          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. 最后,您可以使用 EventBus 到 publish 和 registerHandler 无论如何 .ts 使用导入的文件 ConsoleService .

    我希望这会有所帮助:)

    推荐文章