Flask-SocketIO,私人消息传递和join_room()问题

时间:2019-03-03 22:23:22

标签: flask socket.io flask-login flask-socketio

我无法在本教程中添加私人房间:https://codeburst.io/building-your-first-chat-application-using-flask-in-7-minutes-f98de4adfa5d

我还使用flask-login创建用户登录配置文件。我已经缩小了最简单的解决方案,以创建一个供用户使用join_room()加入的房间。我试图将其实现到我的代码中,但是我一定做错了,因为没有任何效果。到目前为止,这是我的代码:

Python:

@app.route('/message/<string:chat_id>/', methods=['GET', 'POST'])
@login_required
def message(chat_id):
    return render_template('message.html', currentuser = \
                          str(current_user.username), chatid = chat_id)

def messageReceived(methods=['GET', 'POST']):
    print('message was received!!!')

@socketio.on('join')
def on_join(data):
    username = data['username']
    room = data['room']
    join_room(room)
    send(username + ' has entered the room.', room=room)

@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
    print('received my event: ' + str(json))
    socketio.emit('my response',  json, callback=messageReceived)

HTML:

    

<form action="" method="POST">
  <input type="text" class="message" placeholder="Messages"/>
  <input type="submit"/>
</form>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script type="text/javascript">
  var user_name = "{{currentuser}}"
  var socket = io.connect();

  socket.emit('join', {
    username : '{{currentuser}}',
    room : '{{chatid}}'
  })

  socket.on( 'connect', function(socketio) {
    socket.emit( 'my event', {
      data: 'User Connected'
    } )
    var form = $( 'form' ).on( 'submit', function( e ) {
      e.preventDefault()
      let user_input = $( 'input.message' ).val()
      socket.emit( 'my event', {
        user_name : user_name,
        message : user_input
      } )
      $( 'input.message' ).val( '' ).focus()
    } )
  } )

  socket.on( 'my response', function( msg ) {
    console.log( msg )
    if( typeof msg.user_name !== 'undefined' ) {
      $( 'h3' ).remove()
      $( 'div.message_holder' ).append( '<div><b>'+msg.user_name+'</b> '+msg.message+'</div>' )
    }
  })
</script>

在两个单独的浏览器中的localhost上运行此代码时,两个用户都可以看到消息。使用打印功能,我已经验证了@ socketio.on('join')函数中声明的room变​​量在两个用户之间是否不同。运行代码时不会引发任何错误。任何帮助或为我指明正确的方向,将不胜感激!

0 个答案:

没有答案