WebSocket握手期间出错:意外的响应代码:角度为

时间:2019-08-20 10:34:00

标签: websocket angular6 angular5

我已经按照https://tutorialedge.net/typescript/angular/angular-websockets-tutorial/中的教程进行操作 我正在尝试建立Websocket连接,但是套接字连接后却出现错误。该错误显示为“ WebSocket握手期间发生错误:意外的响应代码:502”

我已经按照本教程进行了操作,但是按照步骤进行操作,但是在连接套接字后仍然出现错误。

  

websocket.service.ts

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


@Injectable({
providedIn: 'root'
})
export class WebsocketService {


constructor() { }

private subject: Rx.Subject<MessageEvent>;
public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
  this.subject = 
this.create('ws://61c725fa.ngrok.io/auth/forgot_password/');
  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);
}

}

notifier.service.ts

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


let ws_scheme = window.location.protocol == "https:" ? "wss" : 
"ws";
let ws_path = ws_scheme + '://' +"61c725fa.ngrok.io" +
"/auth/forgot_password/";
const URL = ws_path;

export interface Message {
username: string;
}

@Injectable({
providedIn: 'root'
})
export class NotifierService {
public messages: Subject<Message>;

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

component.ts

import { Component } from '@angular/core';
import { NotifierService } from './notifier.service';


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


title = 'ang-socket';
constructor(private notifier:NotifierService){
notifier.messages.subscribe(msg=>{
  console.log("response from websocket:" + msg);

})
}

private message = {
username: "abc@gmail.com"
};

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


}

我想解决此问题。如果有人帮忙,那就太好了。

0 个答案:

没有答案