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

问题描述

我在前端使用 Angular2 webapp 项目,后端使用 Vertex3.

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

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

npm 安装 sockjs 客户端

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

从 'sockjs-client' 导入 * 作为 SockJS;

导出类 LoginService {URL: string = 'http://localhost:8082/eventbus';袜子:SockJS;处理程序 = {};私人 _opened:布尔值 = 假;公共开放():无效{如果(!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;}公共 isOpen(): 布尔 {返回 this._opened;}公共关闭():无效{如果(this._opened){this.sock.close();删除this.sock;this._opened = false;}}私信收到 (e) {var msg = JSON.parse(e.data);this.callHandlers('message', msg.type, msg.originator, msg.data);}private callHandlers (type: string, ...params: any[]) {如果(this.handlers[type]){this.handlers[type].forEach(function(cb) {cb.apply(cb, params);});}}公共发送(类型:字符串,数据:任何){如果(this._opened){var msg = JSON.stringify({类型:类型,数据:数据});this.sock.send(msg);}}}

使用

运行 angular2 webapp 项目时没有错误

npm 运行服务器

但是没有在客户端创建 websocket 连接.因为我已经使用顶点 vertex.createHttpServer (托管在:http://localhost:8082).

所以我有两个问题:

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

2. 构建 angular2 webapp 项目时出错,因为在 node_modules 中找不到sockjs-client"(奇怪的是它存在于 node_modules 中)

有什么我遗漏的吗?

提前致谢!!!

解决方案

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

使用以下步骤:

  1. index.html
  2. 中导入sockjs-event.jssockjs-client.js

 
  1. 创建导出服务 myapp.service.ts

 声明 var EventBus: any;@Injectable()导出类 ConsoleService {URL: string = 'http://localhost:8082/eventbus';处理程序 = {};事件总线:任何;私人 _opened:布尔值 = 假;公共开放():无效{如果(!this._opened){this.eventBus = new EventBus(this.URL);this.eventBus.onopen = (e) =>{this._opened = true;console.log("打开连接");this.callHandlers('open', e);this.eventBus.publish("http://localhost:8082", "用户登录信息");this.eventBus.registerHandler("http://localhost:8081/pushNotification", function (error, message) {控制台日志(消息.正文);//$("<div title='Basic dialog'>测试消息</div>").dialog();});}this.eventBus.onclose = (e) =>{this.callHandlers('close', e);}}}公共 isOpen(): 布尔 {返回 this._opened;}公共关闭():无效{如果(this._opened){this.eventBus.close();删除this.eventBus;this._opened = false;}}......公共发送(类型:字符串,数据:任何){如果(this._opened){var msg = JSON.stringify({类型:类型,数据:数据});this.eventBus.publish("http://localhost:8082",msg);}}};导出默认的 ConsoleService;
  1. 在我的情况下,转到您的起始模块 app.module.ts 并在 angular bootstrap 中加载您的服务 myapp.service.ts

 import { AppComponent } from './app.component';....从'services/myapp.service'导入{ ConsoleService};@NgModule({进口:[....],提供者:[ ConsoleService ],声明: [应用组件,...],引导程序:[AppComponent]})

4.从你的起始组件app.component.ts

调用打开的websocket
 import { Component } from '@angular/core';导入样式/app.scss";从'services/globalConsole.service'导入{ ConsoleService};@零件({selector: 'my-app',//<my-app></my-app>templateUrl: './app.component.html',styleUrls: ['./app.component.scss']})导出类 AppComponent {构造函数(私有控制台服务:ConsoleService){consoleService.onOpen((e) => {consoleService.send('message', "xyz");});consoleService.open();}}
  1. 最后,您可以使用 EventBus 使用 import 在任何 .ts 文件中publishregisterHandlerConsoleService .

我希望这会有所帮助:)

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

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

I have installed sockjs-client using npm :

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


}

no errors while running angular2 webapp project using

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).

So I have two issues :

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

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 )

Is there anything I'm missing ?

Thanks in Advance !!!

解决方案

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

Use Following steps:

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

  }

I hope this will help :)

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

06-09 14:31