如何建立从angular-socketio到flask-socketio的websocket连接

时间:2019-09-03 03:59:10

标签: angular flask flask-socketio angular-socket-io

我是Web套接字的新手,我正在使用flask-socketio和angular-socketio作为客户端来实现Web套接字服务器,

我在烧瓶中使用此代码

  

application.py

@socketio.on('connect', namespace='/test')
def test_connect():    
    print('Client connected')

我在角度服务中使用此代码连接到烧瓶服务器

  

socket.service.ts

    import { Injectable } from "@angular/core";
    import * as io from "socket.io-client";
    import { Observable } from "rxjs";

    @Injectable({
      providedIn: "root"
    })
    export class SocketService {      
      private socket;

      constructor() {        
        this.socket = io("/test"); // i get example by connect using flask namespace
this.socket = io("localhost:5000"); // i tried this
this.socket = io(`/api`); // i also tried this

      }

      public sendMessage(message) {
        this.socket.emit("new-message", message);
      }

      public getMessages = () => {
        return Observable.create(observer => {
          this.socket.on("new-message", message => {
            observer.next(message);
          });
        });
      };
    }

我还尝试使用localhost:5000作为URL连接到flask服务器,但是这会导致CORS问题,并且在遇到该问题后,我还尝试使用来自以下proxy.config.json的'/ api'作为URL进行连接。

{
  "/api": {
  "target": "http://127.0.0.1:5000",
  "secure": false,
  "pathRewrite": {
      "^/api": ""
  }
  }
}

这是我的app.component

  

app.component.ts

import { Component } from "@angular/core";
import { SocketService } from "./socket.service";

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

  constructor(private socketService: SocketService) {}
}

1 个答案:

答案 0 :(得分:0)

如果需要跨域访问Socket.IO服务器,则需要对其进行适当的配置。请参见documentation中的cors_allowed_origins选项。

Socket.IO服务的默认URL为/socket.io。如果要使用其他URL,则需要告知客户端和服务器。对于服务器,这是path选项,也是documented