如何使用websockets将消息发送到后端

时间:2017-07-29 11:26:35

标签: javascript angular typescript websocket

我正在尝试使用PostgreSQL数据库在Django后端和Angular 4前端之间创建实时聊天。我们假设我想创建聊天机器人,例如A.L.I.C.E。我不确定,但在我看来,最佳解决方案是使用websockets?我想在前端写消息,按回车键并将我的消息发送到后端。然后我想得到回应。我试图以下面显示的方式执行此操作,但是我收到错误。我想在前端输入我自己的文字,按回车键发送。

app.component.html:

<button (click)="sendMsg()">Send Message</button>

<h4>Type away! Press [enter] when done.</h4>
<div><key-up3 (keyup7)="send($event)"></key-up3></div>

app.component.ts:

import { Component } from '@angular/core';
import { WebsocketService } from './websocket.service';
import { ChatService } from './chat.service';
import { Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ WebsocketService, ChatService ]
})
export class AppComponent {

    constructor(private chatService: ChatService) {
        chatService.messages.subscribe(msg => {
      console.log("Response from websocket: " + msg);
        });
    }

    private message = {
        message: 'this is a test message'
    }

  sendMsg() {
        console.log('new message from client to websocket: ', this.message);
        this.chatService.messages.next(this.message);
        this.message.message = '';
    }

  send(msg) {
     this.message = msg;
     this.sendMsg();
  }

}

@Component({
  selector: 'key-up3',
  template: `
    <input #box (keyup.enter)="keyup7.emit(box.value)">
    <p>{{value}}</p>
  `
})
export class KeyUpComponent_v3 {
   @Output() keyup7 = new EventEmitter<string>();
}

websocket.service.ts:

import { Injectable } from '@angular/core';
import * as Rx from 'rxjs/Rx';

@Injectable()
export class WebsocketService {
  constructor() { }

  private subject: Rx.Subject<MessageEvent>;

  public connect(url): Rx.Subject<MessageEvent> {
    if (!this.subject) {
      this.subject = this.create(url);
      console.log("Successfully connected: " + url);
    }
    return this.subject;
  }

  private create(url): Rx.Subject<MessageEvent> {
    let ws = new WebSocket(url);

    let observable = Rx.Observable.create(
    (obs: Rx.Observer<MessageEvent>) => {
        ws.onmessage = obs.next.bind(obs);
        ws.onerror = obs.error.bind(obs);
        ws.onclose = obs.complete.bind(obs);
        return ws.close.bind(ws);
    })
let observer = {
        next: (data: Object) => {
            if (ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify(data));
            }
        }
    }
    return Rx.Subject.create(observer, observable);
  }

}

chat.service.ts:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import { WebsocketService } from './websocket.service';

const CHAT_URL = 'ws://localhost:8000/';

export interface Message {
    message: string
}

@Injectable()
export class ChatService {
    public messages: Subject<Message>;

    constructor(wsService: WebsocketService) {
        this.messages = <Subject<Message>>wsService
            .connect(CHAT_URL)
            .map((response: MessageEvent): Message => {
                let data = JSON.parse(response.data);
                return {
                    message: data.message
                }
            });
    }
}

更新 模板中的KeyUp.emit(box.value)在组件中有upercase K.是小写的。但是,此时我写东西并按回车键没有任何反应。有什么建议吗?

更新后出错: enter image description here

1 个答案:

答案 0 :(得分:0)

您可以将一个EventEmitter添加到您的keyUp组件

<!-- https://mvnrepository.com/artifact/org.apache.zeppelin/zeppelin-zengine -->
<dependency>
    <groupId>org.apache.zeppelin</groupId>
    <artifactId>zeppelin-zengine</artifactId>
    <version>0.7.2</version>
</dependency>

然后在您的主要组件中侦听该事件并相应地设置消息值。您将要公开您的import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'key-up3', template: ` <input #box (keyup.enter)="keyUp.emit(box.value)"> <p>{{value}}</p> ` }) export class KeyUpComponent_v3 { @Output() keyUp = new EventEmitter<string>(); } 属性,以便可以设置模板。

message

另外:

RxJS有一个名为WebSocketSubject的类,您可以使用它来轻松地从您的服务器发送和接收消息,这是一个服务的快速示例。

<h4>Type away! Press [enter] when done.</h4>
<div><key-up3 (keyUp)="message = $event"></key-up3></div>

import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Rx'; @Injectable() export class SocketServer { private webSocket$ = Observable.webSocket('ws://localhost:3000/'); public asObservable(): Observable<any> { return this.webSocket$.retry(); } public sendData(value) { this.webSocket$.next(value); } } 如果断开连接,将尝试重新连接到WebSocket