websocket Flask SocketIO和Angular socket.io-client中的CORS策略错误

i7uq4tfw  于 12个月前  发布在  Angular
关注(0)|答案(1)|浏览(152)

我正在尝试使用Flask和Angular学习WebSocket,但无法解决CORS问题。即使我允许CORS,我的Angular客户端WebSocket也无法连接到Flask服务器WebSocket。下面,我添加了我的代码Angular和Flask。这两个都非常简单,因为我只是试图建立连接。

server.py

from flask import Flask
from flask_socketio import SocketIO, send, emit
from flask_cors import CORS, cross_origin 

app = Flask(__name__)

app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins="*")
CORS(app)

@socketio.on('message')
@cross_origin()
def handle_message(data):
    print('received message: ' + data)
    send("test message that should be sent")

if __name__ == '__main__':
    socketio.run(app, host="localhost")

字符串

app.component.html

<div *ngFor="let message of messageList">
    <li>
        {{message}}
    </li>
  </div>
  
  <input
    [(ngModel)]="newMessage"
    (keyup)="$event.keyCode == 13 && sendMessage()"
  />
  <button (click)="sendMessage()">Send Message</button>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { WebsocketService } from './services/websocket.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  newMessage = '';
  messageList: string[] = [];

  constructor(private websocket: WebsocketService){
  }

  ngOnInit(){
    this.websocket.getNewMessage().subscribe((message: string) => {
      this.messageList.push(message);
    })
  }

  sendMessage() {
    this.websocket.sendMessage(this.newMessage);
    this.newMessage = '';
  }
}

WebSocket.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { io } from 'socket.io-client';

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

  public message$: BehaviorSubject<string> = new BehaviorSubject('');
  constructor() {}

  socket = io('http://localhost:5000');

  public sendMessage(message: any) {
    console.log('sendMessage: ', message)
    this.socket.emit('message', message);
  }

  public getNewMessage = () => {
    this.socket.on('message', (message) =>{
      this.message$.next(message);
    });

    return this.message$.asObservable();
  };
}


最后,这是错误:Error

rpppsulh

rpppsulh1#

我的电脑是macOS,很明显,有一个名为AirPlay Receiver的服务使用端口5000。它正在“拖”我的WebSocket服务器并导致问题。您可以在系统偏好设置>共享> AirPlay Receiver中禁用它或更改服务器端的端口。我从未尝试过第二种解决方案,因为当我检查端口状态时,我已经在运行server.py,这误导了我。

相关问题