我的项目无法在 socketio 上捕获发出的消息,即使它已连接到套接字

问题描述 投票:0回答:0

这是我的 Flask 应用程序

import eventlet
import json
import pika
import nltk
import string
import threading
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from flask_cors import CORS

# Initialize the Flask app and Socket.IO
app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app,cors_allowed_origins="*")

# Initialize NLTK
nltk.download('words')
nltk.download('webtext')
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')

# Initialize RabbitMQ connection and channel
# Initialize RabbitMQ connection and channel
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost',heartbeat=0))
channel = connection.channel()
channel.queue_declare(queue='nlp_queue')


# Socket.IO route to render the main HTML page
@app.route('/')
def index():
    return render_template('index.html')

# Socket.IO event handler for the 'connect' event
@socketio.on('connect')
def handle_connect():
    print('Angular Client connected')

# Socket.IO event handler for the 'disconnect' event
@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')


@app.route('/send-sync',methods=["GET"])
def send_sync():
    text = nltk.corpus.webtext.raw('grail.txt')
    textWithoutPunc =  text.translate(str.maketrans('', '',string.punctuation))
    wordsWithoutPunc = nltk.word_tokenize(textWithoutPunc)
    fd = nltk.FreqDist(wordsWithoutPunc)
    tokenized    = nltk.word_tokenize(textWithoutPunc)
    tagged = nltk.pos_tag(tokenized)
    named_ent    = nltk.ne_chunk(tagged)
  
    return ({"status":"Returned"})

# Flask route to send a message to the RabbitMQ queue
@app.route('/send-async',methods=["GET"])
def send_message():
    text = nltk.corpus.webtext.raw('grail.txt')
    textWithoutPunc = text.translate(str.maketrans('', '', string.punctuation))
    wordsWithoutPunc = nltk.word_tokenize(textWithoutPunc)
    fd = nltk.FreqDist(wordsWithoutPunc)
    tokenized = nltk.word_tokenize(textWithoutPunc)
    tagged = nltk.pos_tag(tokenized)
    named_ent = nltk.ne_chunk(tagged)

    channel.basic_publish(exchange='', routing_key='nlp_queue', body=json.dumps(named_ent))
    print("Sent message: ", 'worked async')
    return ({"status": "Message sent to queue !" })

# Function to process messages from the RabbitMQ queue
def process_message(ch, method, properties, body):
    print("message is processed")
    named_entities = json.loads(body)
    try:
        socketio.emit('nlp', named_entities) # Emit the message to the Socket.IO server
        print(socketio)

    except Exception as e:
        print("Error emitting message:", e)

# Function to consume messages from the RabbitMQ queue
def consume():
    channel.basic_consume(queue='nlp_queue', on_message_callback=process_message, auto_ack=True)
    channel.start_consuming()


# Socket.IO event handler for the 'connect' event
@socketio.on('connect')
def handle_connect():
    print('Client connected')

# Socket.IO event handler for the 'disconnect' event
@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')


# Define a function to run the consume() function in a separate thread
def start_consuming():
    t = threading.Thread(target=consume)
    t.daemon = True
    t.start()


# Start the Flask and Socket.IO server
if __name__ == '__main__':
    eventlet.monkey_patch() # Patch the standard library for use with Socket.
    socketio.run(app, host='0.0.0.0', port=5000, debug=True)
    consume()

这是我的 Angular 应用程序

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Socket } from 'ngx-socket-io';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  title = 'termproject-ui';
  messages: any[] = [];
  msg: any;
  constructor(private http: HttpClient, private socket: Socket) {}

  ngOnInit() {
    console.log(this.socket);
    this.socket.on('connect', () => {
      console.log('Socket connected successfully');
    });
    this.socket.on('nlp', (message: any) => {
      console.log('message incomed');
      console.log('Received message:', message);
      this.messages.push(message);
    });

    this.socket.on('disconnect', function () {
      console.log('Socket disconnected');
    });

    this.socket.on('error', function onSocketError(e: any) {
      console.log('WebSocket Error ' + e);
    });
    this.msg = this.socket.fromEvent<any>('message');
    this.socket.fromEvent<any>('test').subscribe((message: any) => {
      console.log('Received message:', message);
      this.messages.push(message);
    });
  }

  onLoadSyncClick(event: any) {
    console.log(this.socket);
    this.http
      .get<any[]>('http://192.168.1.95:5000/send-sync')
      .subscribe((data) => {
        this.socket.emit('test', 'Hello from Angular');

        console.log(data);
      }),
      (err: any) => {
        console.log(err);
      };
  }
  onLoadAsyncClick(event: any) {
    console.log(this.socket);
    this.http
      .get<any[]>('http://192.168.1.95:5000/send-async')
      .subscribe((data) => {
        console.log(data);
        console.log(this.messages);
        this.socket.emit('test', 'Hello from Angular');
      }),
      (err: any) => {
        console.log(err);
      };
  }
}
import { DxButtonModule } from 'devextreme-angular';
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://192.168.1.95:5000', options: {} };
@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    DxButtonModule,
    SocketIoModule.forRoot(config),
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

我不明白为什么我发出的消息没有被捕获,甚至在我发送消息时 console.log 也不起作用。我能够看到连接成功完成并且 flask 中 process_messages 函数中的打印语句工作正常。但是,当我发送消息时,前端有任何变化。

angular sockets socket.io flask-socketio
© www.soinside.com 2019 - 2024. All rights reserved.