Angular5,socket.io-client和Ratchet Websocket因HTTP 426错误而失败

时间:2018-03-17 14:28:31

标签: angular websocket socket.io ratchet

我正在使用Angular应用程序,它必须与Websocket服务器通信。 ws服务器正在监听192.168.1.99:8080并由Ratchet / Websocket(在PHP下)提供支持。

服务器正在按预期运行,并且允许本地主机:4200'作为值得信赖的客户。

在客户端,使用管理连接和消息交换的服务:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

import * as io from 'socket.io-client';

import { Constants } from './../../constants/constants';

@Injectable()
export class WebsocketService {

  private _socket: any;

  constructor() { }

  public sendMessage(messageType: string, message: any){
    this._socket.emit(
      messageType,
      message
    );
  }

  public getMessages(): Observable<any> {
    let observable = new Observable((observer) => {
      this._socket = io(Constants._WS_URL);
      this._socket.on(
        'message',
        (data) => {
          observer.next(data);
        }
      );

      return () => {
        this._socket.disconnect();
      };

    });

    return observable;
  }
}

没什么特别......只是现有代码的复制/粘贴。

我的组件实现onInit并执行以下操作:

  ngOnInit() {
    // websocket instanciation
    this._wsConn = this.websocketService.getMessages().subscribe((message) 
        => {
          this._messages.push(message);
    });
}

当应用运行时,得到:

http://192.168.1.99:8080/socket.io/?EIO=3&transport=polling&t=M8qMAFE 426 (Upgrade header MUST be provided)

(index):1 Failed to load http://192.168.1.99:8080/socket.io/?EIO=3&transport=polling&t=M8qMAFE: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 426.

花了几个小时来寻找从客户端发送标题的方式,以及大量的咖啡,没有找到任何想法......

注意......尝试通过Websocket纯Javascript进行通信,一切都很好:

var conn = new WebSocket('ws://192.168.1.99:8080');
conn.onopen = function(event){
    console.log('Connexion au serveur établie');
}

conn.onmessage = function (event){
    console.log('Message reçu ' + event.data);
}

Websocket服务器日志......

/mnt/c/webroot/ws_stestex$ php index.php
Initialise le traitement périodique
Nouvelle connexion : 7036

所以,我的问题是......我该怎么办?洛尔...

嗯..我将服务方法更改为:

      this._socket = io('ws://192.168.1.99:8080', {
    transportOptions: {
      polling: {
        extraHeaders: {
          'x-clientid': 'saintesaintex',
          'Sec-WebSocket-Version': '13'
        }
      }
    }
  });

然后我收到405 HTTP错误......有人能告诉我正确的标题吗?

注意2:当我检查网络控制台时,看到它不是使用的ws协议但是http ...

0 个答案:

没有答案