Web chat room realized by flash socket IO

Posted by damic on Sun, 06 Mar 2022 21:00:24 +0100

preface

As a Xiaobai, it's really difficult to read documents, and there is little knowledge about flash socketio on the Internet, so I wrote this blog for some brothers who can't do anything like me to understand the basic use of flash socketio, which can also be regarded as recording the production process of my chat room, even my small log, If you want to see the back-end detailed code, you can click Last blog
If you want to run with the code directly, you can visit my website directly github
If you can't run after downloading, it was also mentioned in the last blog, so I won't repeat it here

Current effect


1, What was added this time

  • Automatic roller
  • Some treatment of spaces and angle brackets
  • Room function

2, How did it happen

1. Roller

This uses a section of js code, as follows:
messageBox is the large white box where messages are placed. It is a div element. If the content overflows, the setting wheel is implemented through css

overflow-y: scroll;
messageBox.scrollTop = messageBox.scrollHeight

2. Space angle brackets

Because my information is placed through a div (see a blog or github for details), angle brackets or spaces can't be displayed
You need to do a little operation on the back end
As you can see, in data ['message'] = data Get ('message ')... String replacement is performed here, so that spaces or angle brackets can be displayed in html

@socketio.on('send msg')
def handle_message(data):
    print('sendMsg' + str(data))
    room = session.get('room')
    data['message'] = data.get('message').replace('<', '&lt;').replace('>', '&gt;').replace(' ', '&nbsp;')
    socketio.emit('send msg', data, to=room)

3. Room

Official documents explain this

For many applications, it is necessary to group users into subsets that can be processed together. The best example is a chat application with multiple rooms, where users receive messages from one or more of their rooms rather than from other rooms where other users are located. join_ Room () flame socketio pass and leave_ The room () function supports this room concept

My feeling is to realize a tool of single chat and group chat. Single chat is to provide a room number that only both parties know, and group chat is to provide a room number that a group of people know
Then I read the official documents and looked confused. Then I went to bilibili and watched some chat room videos. I turned to the relevant explanations in the book "flash web development practice". I probably understood the thing of room, Except that you may need to give the back-end room number in the previous paragraph (or not, for example, a friend platform, click the friend name, chat with friends, and the room number should be provided by the back-end), you don't need to write anything else in the front-end.
Where are the changes in the back-end room?
Listen to me slowly

When logging in

When we look at the flash function, we can find that room is accepted in the post method and exists in the session

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        if 'username' in session:
            return redirect(url_for('chat'))
        return render_template('index.html')
    else:
        username = request.form.get('username')
        room = request.form.get('room')
        session['username'] = username
        session['room'] = room
        return redirect(url_for('chat'))

Chat page

Here we import room into the template to display the room name

@app.route('/chat/')
def chat():
    if 'username' in session and 'room' in session:
        username = session['username']
        room = session['room']
        return render_template('chat.html', username=username, room=room)
    else:
        return redirect(url_for('index'))

Send message

At the end of this event listening function, we can find that there is an additional to parameter. What we pass in is the room name

@socketio.on('send msg')
def handle_message(data):
    print('sendMsg' + str(data))
    room = session.get('room')
    data['message'] = data.get('message').replace('<', '&lt;').replace('>', '&gt;').replace(' ', '&nbsp;')
    socketio.emit('send msg', data, to=room)

Join and leave the room

front end
As you can see here, once you enter this page, an event will be automatically triggered and sent to the back end
Leaving the room is achieved by setting click events for hyperlinks

// Join the room
   socket.emit('join', {
       username: username,
       room: room
   })
   // Exit the room
   leaveroom.onclick = function () {
       socket.emit('leave', {
           username: username,
           room: room
       })
   }

back-end
In the back-end code, you need to use the join provided by flash socket io_ Room and leave_room method, just pass in the room name, and then when sending information, you still need to specify the to parameter as the room name

@socketio.on('join')
def on_join(data):
    username = data.get('username')
    room = data.get('room')
    try:
        room_user[room].append(username)
    except:
        room_user[room] = []
        room_user[room].append(username)

    join_room(room)
    print('join room:  ' + str(data))
    print(room_user)
    socketio.emit('connect info', username + 'Join the room', to=room)


@socketio.on('leave')
def on_leave(data):
    username = data.get('username')
    room = data.get('room')
    room_user[room].remove(username)
    leave_room(room)
    print('leave room   ' + str(data))
    print(room_user)
    socketio.emit('connect info', username + 'Leave the room', to=room)

summary

If there are still some perfect aspects in this chat room, I will continue to write a blog to record my hard work as Xiaobai, and hope to help other Xiaobai [doge]

Topics: Python Back-end Flask