如何使用Python Flask、socket.io构建聊天功能?

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

我有一个学校项目,需要我的团队构建一个应用程序,我的任务是执行聊天/消息传递功能。在过去的两周里,我一直在尝试弄清楚如何构建它,但尽管尝试遵循在线教程,但我仍然失败。老实说,编程不是我的菜,但这个项目占了模块中的大部分。因此,我别无选择,只能呈现一些可以接受的东西。

大多数在线教程都像聊天室。基本上,用户必须创建一个房间,然后另一个用户将使用创建的房间代码加入聊天。但在我的项目中,用户已经创建。它就像一个消息传递应用程序,其中有其他用户(您可以与之聊天的人)和聊天本身的侧边栏。我不知道如何才能做到这一点。任何形式的帮助将不胜感激=)

python flask flask-socketio
1个回答
0
投票

对于 Flask-Socketio,我建议阅读这些指南: https://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent https://flask-socketio.readthedocs.io/en/latest/getting_started.html#

最终,您将需要

Flask-Socketio
包位于您的后端。使用上述步骤进行设置。

在前端,我假设您正在使用 ReactJS。常用的包是

socket.io-client

import React, { Component } from 'react';
import { io } from 'socket.io-client';

// initialize outside of the class
let socket;

class Chat extends Component {

  constructor(props) {
    super(props);
    this.state = {
      text: null
    }
    this.handleChatSend = this.handleChatSend.bind(this);
    this.handleTextChange = this.handleTextChange.bind(this);
  }

  componentDidMount() {
    let server;
    let domain;
    // a very simple way to connect offline is to use your localhost domain.
    // generally, you should specify the origin (the client hostname & port) 
    // as well as the server.  If you host in production (ie. anywhere other 
    // than localhost) the else statement will catch that.
    if (window.location.hostname === 'localhost') {
      server = `${window.location.hostname}:3000`;
      domain = `http://${window.location.hostname}:8000`;
    } else {
      server = window.location.hostname;
      domain = window.location.hostname;
    }
    socket = io(`http://${server}`, {
      cors: {
          origin: domain,
          methods: ["GET", "POST"],
          transports: ['websocket', 'polling'],
          credentials: true
      },
      transports: ['websocket', 'polling'],
      withCredentials: true,
      allowEIO3: true
    });

    // this down here is your listener.  Your backend needs to call 
    // emit("message send") with some sort of payload which will be 
    // available in the argument serverData, you need to have your listeners
    // running on your Frontend before making any calls to your Backend.
    socket.on("message send", (serverData) => {
      let data = JSON.parse(serverData);
      this.setState({
        // do something here to store your state of chat messages
      });
    })
  }

  handleChatSend(text) {
    if (this.state.text !== null) {
      socket.emit("submit message", { text: this.state.text});
      this.setState({ text: null });
    }
  }

  handleTextChange(e) {
    e.preventDefault();
    this.setState({ text: e.target.value });
  }
  render() {
    // in the render function set up your JSX to render these messages, 
    // include a text field and buttons to interact with these functions to 
    // help you perform basic chat functions
    return (
      <div>
        <-- your elements --/>
      </div>
    )
  }
}

在后端,您需要初始化您的socketio包并与您的应用程序一起运行它,但在您的routes.py中,至少,您需要一个位于

"submit message"
的侦听器,当您处理完该信息时,您的后端处理程序,您将把它发送回您的前端侦听器
"message send"
:

from flask_socketio import emit

# Socketio setup goes here in your code
# read the guides above to initialize your socketio in Flask

# then you can listen to things sent from your client:
@socketio.on("submit message")
def message_received(data):
  emit("message send", data, broadcast=True)
© www.soinside.com 2019 - 2024. All rights reserved.