Flask-SocketIO服务端安装及使用代码示例


Posted in Python onNovember 26, 2020

安装Flask-Sockets很容易:

pip install flask-socketio

注意Flask-SocketIO依赖gevent库,目前它仅可以在python2上运行(译者注:python3.6测试也可以)。gevent很快也会对python3支持。

下面是一个Flask-SocketIO在Flask应用上的实现例子:

from flask import Flask, request, jsonify,render_template
from flask_socketio import SocketIO, emit


app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)


@app.route('/')
def index():
  return render_template('test.html')

#触发事件my event:回复只发送此连接
@socketio.on('my_event', namespace='/chat')
def test_message(message):
  print(message)
  emit('my_response', {'data': message['data']})


#触发事件my broadcast event::回复所有链接(广播)
@socketio.on('my_broadcast event', namespace='/chat')
def test_message(message):
  print(message)
  emit('my_response', {'data': message['data']}, broadcast=True)

##################################################################
#自动连接和自动断开触发
@socketio.on('connect', namespace='/chat')
def test_connect():
  print("连接到来")
  emit('my_response', {'data': 'Connected'})

@socketio.on('disconnect', namespace='/chat')
def test_disconnect():
  print("连接断开")
  print('Client disconnected')

if __name__ == '__main__':
  socketio.run(app,host='0.0.0.0',port=8200,debug=True)

对应的test.html,注意一个问题:flask是从与启动文件同级的templates查找模板的。

test.html

官方完整示例

#!/usr/bin/env python
from threading import Lock
from flask import Flask, render_template, session, request, \
  copy_current_request_context
from flask_socketio import SocketIO, emit, join_room, leave_room, \
  close_room, rooms, disconnect

# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on installed packages.
async_mode = None

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()

def background_thread():
  """Example of how to send server generated events to clients."""
  count = 0
  while True:
    socketio.sleep(100)
    count += 1
    socketio.emit('my_response',
           {'data': 'Server generated event', 'count': count},
           namespace='/test')

@app.route('/')
def index():
  return render_template('test1.html', async_mode=socketio.async_mode)

@socketio.on('my_event', namespace='/test')
def mtest_message(message):
  print(message)
  session['receive_count'] = session.get('receive_count', 0) + 1
  # print(message)
  # print(message['data'])
  emit('my_response',
     {'data': message['data'], 'count': session['receive_count']})

@socketio.on('my_broadcast_event', namespace='/test')
def mtest_broadcast_message(message):
  print(message)
  session['receive_count'] = session.get('receive_count', 0) + 1
  emit('my_response',
     {'data': message['data'], 'count': session['receive_count']},
     broadcast=True)

@socketio.on('join', namespace='/test')
def join(message):
  print(message)
  join_room(message['room'])
  session['receive_count'] = session.get('receive_count', 0) + 1
  emit('my_response',
     {'data': 'In rooms: ' + ', '.join(rooms()),
     'count': session['receive_count']})

@socketio.on('leave', namespace='/test')
def leave(message):
  print(message)
  leave_room(message['room'])
  session['receive_count'] = session.get('receive_count', 0) + 1
  emit('my_response',
     {'data': 'In rooms: ' + ', '.join(rooms()),
     'count': session['receive_count']})

@socketio.on('close_room', namespace='/test')
def close(message):
  session['receive_count'] = session.get('receive_count', 0) + 1
  emit('my_response', {'data': 'Room ' + message['room'] + ' is closing.',
             'count': session['receive_count']},
     room=message['room'])
  close_room(message['room'])

@socketio.on('my_room_event', namespace='/test')
def send_room_message(message):
  session['receive_count'] = session.get('receive_count', 0) + 1
  emit('my_response',
     {'data': message['data'], 'count': session['receive_count']},
     room=message['room'])


##################################################################
#自动连接和自动断开触发
@socketio.on('connect', namespace='/test')
def test_connect():
  print("连接到来")
  emit('my response', {'data': 'Connected'})

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
  print("连接断开")
  print('Client disconnected')


if __name__ == '__main__':
  socketio.run(app, debug=True,port= 8200)

test1.html

<!DOCTYPE HTML>
<html>
<head>
  <title>Flask-SocketIO Test</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
  <script type="text/javascript" charset="utf-8">
      $(document).ready(function(){
     var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
       socket.on('my_response', function(msg) {
         $('#log').append('<p>Received: ' + msg.data + '</p>');
    });

      $('form#emit').submit(function(event) {
        socket.emit('my_event', {data: $('#emit_data').val()});
        return false;
      });
      $('form#broadcast').submit(function(event) {
        socket.emit('my_broadcast_event', {data: $('#broadcast_data').val()});
        return false;
      });
      $('form#join').submit(function(event) {
        socket.emit('join', {room: $('#join_room').val()});
        return false;
      });
      $('form#leave').submit(function(event) {
        socket.emit('leave', {room: $('#leave_room').val()});
        return false;
      });
      $('form#send_room').submit(function(event) {
        socket.emit('my_room_event', {room: $('#room_name').val(), data: $('#room_data').val()});
        return false;
      });
      $('form#close').submit(function(event) {
        socket.emit('close_room', {room: $('#close_room').val()});
        return false;
      });
      $('form#disconnect').submit(function(event) {
        socket.emit('disconnect_request');
        return false;
      });
    });
  </script>
</head>
<body>
  <h1>Flask-SocketIO Test</h1>
  <p>Async mode is: <b>{{ async_mode }}</b></p>
  <p>Average ping/pong latency: <b><span id="ping-pong"></span>ms</b></p>
  <h2>Send:</h2>
  <form id="emit" method="POST" action='#'>
    <input type="text" name="emit_data" id="emit_data" placeholder="Message">
    <input type="submit" value="Echo">
  </form>
  <form id="broadcast" method="POST" action='#'>
    <input type="text" name="broadcast_data" id="broadcast_data" placeholder="Message">
    <input type="submit" value="Broadcast">
  </form>
  <form id="join" method="POST" action='#'>
    <input type="text" name="join_room" id="join_room" placeholder="Room Name">
    <input type="submit" value="Join Room">
  </form>
  <form id="leave" method="POST" action='#'>
    <input type="text" name="leave_room" id="leave_room" placeholder="Room Name">
    <input type="submit" value="Leave Room">
  </form>
  <form id="send_room" method="POST" action='#'>
    <input type="text" name="room_name" id="room_name" placeholder="Room Name">
    <input type="text" name="room_data" id="room_data" placeholder="Message">
    <input type="submit" value="Send to Room">
  </form>
  <form id="close" method="POST" action="#">
    <input type="text" name="close_room" id="close_room" placeholder="Room Name">
    <input type="submit" value="Close Room">
  </form>
  <form id="disconnect" method="POST" action="#">
    <input type="submit" value="Disconnect">
  </form>
  <h2>Receive:</h2>
  <div id="log"></div>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现socket客户端和服务端简单示例
Feb 24 Python
python按照多个字符对字符串进行分割的方法
Mar 17 Python
Python中__init__.py文件的作用详解
Sep 18 Python
浅谈Tensorflow模型的保存与恢复加载
Apr 26 Python
python中ImageTk.PhotoImage()不显示图片却不报错问题解决
Dec 06 Python
python制作填词游戏步骤详解
May 05 Python
Python3内置模块之json编解码方法小结【推荐】
Dec 09 Python
python利用tkinter实现屏保
Jul 30 Python
python实现加密的方式总结
Jan 19 Python
python小程序基于Jupyter实现天气查询的方法
Mar 27 Python
聊聊Python中关于a=[[]]*3的反思
Jun 02 Python
Python list列表删除元素的4种方法
Nov 01 Python
使用OpenCV校准鱼眼镜头的方法
Nov 26 #Python
最新PyCharm 2020.2.3永久激活码(亲测有效)
Nov 26 #Python
Django-celery-beat动态添加周期性任务实现过程解析
Nov 26 #Python
Django celery异步任务实现代码示例
Nov 26 #Python
Django通过设置CORS解决跨域问题
Nov 26 #Python
Django利用elasticsearch(搜索引擎)实现搜索功能
Nov 26 #Python
python模拟点击在ios中实现的实例讲解
Nov 26 #Python
You might like
PHP编程实现csv文件导入mysql数据库的方法
2017/04/29 PHP
PHP观察者模式定义与用法实例分析
2019/03/22 PHP
laravel多条件查询方法(and,or嵌套查询)
2019/10/09 PHP
javascript 类方法定义还是有点区别
2009/04/15 Javascript
firefo xml 读写实现js代码
2009/06/11 Javascript
IE FF OPERA都可用的弹出层实现代码
2009/09/29 Javascript
JavaScript 申明函数的三种方法 每个函数就是一个对象(一)
2009/12/04 Javascript
JavaScript是否可实现多线程  深入理解JavaScript定时机制
2009/12/22 Javascript
jQuery中jqGrid分页实现代码
2011/11/04 Javascript
JavaScript实现判断图片是否加载完成的3种方法整理
2015/03/13 Javascript
静态页面html中跳转传值的JS处理技巧
2016/06/22 Javascript
浅谈AngularJS中ng-class的使用方法
2016/11/11 Javascript
vue如何获取点击事件源的方法
2017/08/10 Javascript
angular或者js怎么确定选中ul中的哪几个li
2017/08/16 Javascript
Webpack框架核心概念(知识点整理)
2017/12/22 Javascript
Vue 使用计时器实现跑马灯效果的实例代码
2019/07/11 Javascript
在项目vue中使用echarts的操作步骤
2020/09/07 Javascript
[00:12]2018DOTA2亚洲邀请赛 Somnus丶M出阵单挑
2018/04/06 DOTA
浅析python打包工具distutils、setuptools
2018/04/20 Python
解决pandas .to_excel不覆盖已有sheet的问题
2018/12/10 Python
python3文件复制、延迟文件复制任务的实现方法
2019/09/02 Python
如何基于Python实现电子邮件的发送
2019/12/16 Python
Python计算机视觉里的IOU计算实例
2020/01/17 Python
Keras模型转成tensorflow的.pb操作
2020/07/06 Python
CSS3 绘制BMW logo实的现代码
2013/04/25 HTML / CSS
纯HTML5+CSS3制作图片旋转
2016/01/12 HTML / CSS
德国健康生活方式网上商店:Landkaufhaus Mayer
2019/03/12 全球购物
军训感想500字
2014/02/20 职场文书
文化建设工作方案
2014/05/12 职场文书
机电一体化毕业生自荐信
2014/06/19 职场文书
授权委托书范本(单位)
2014/09/28 职场文书
2014年校长工作总结
2014/12/11 职场文书
2015年毕业实习工作总结
2015/05/29 职场文书
学习新党章心得体会2016
2016/01/15 职场文书
如何写好闭幕词
2019/04/02 职场文书
Pycharm 如何设置HTML文件自动补全代码或标签
2021/05/21 Python