flask-socketio + vue-socket.io 组合使用demo
manage.py
import datetime import json from flask_socketio import Namespace, emit, SocketIO, disconnect from flask import Flask, render_template,request app = Flask(__name__) socketio = SocketIO(app,cors_allowed_origins="*") class MyCustomNamespace(Namespace): def __init__(self,namespace): super(MyCustomNamespace, self).__init__(namespace) self.sid = None def on_connect(self): self.sid = request.sid print('建立连接成功!-{}'.format(self.sid)) def on_disconnect(self): print('客户端断开连接!') def close_room(self, room): socketio.close_room(room=self.sid) print('{}-断开连接'.format(self.sid)) def on_my_event(self, data): while True: print(data) socketio.sleep(5) current_date = str(datetime.datetime.now()) dic = {'current_date': current_date} res_json = json.dumps(dic) emit('server_response', res_json) socketio.on_namespace(MyCustomNamespace('/test')) if __name__ == '__main__': socketio.run(app)
Vue 部分
<template> <div> <h1>websocket连接</h1> </div> </template> <script> export default{ data(){ return{ id:'' } }, sockets:{ // 通信的name //这里是监听connect事件 connect: function(){ this.id=this.$socket.id // alert('建立连接') this.$socket.emit('my_event',9999) }, disconnect: function(){ alert('断开连接') }, reconnect: function(){ console.log('重新连接') this.$socket.emit('conect') }, server_response: function(data){ console.log('接收数据',data) } }, mounted(){ this.$socket.emit('connect'); //在这里触发connect事件 } } </script> <style> </style>
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' Vue.config.productionTip = false // 引入socket.io import VueSocketIO from 'vue-socket.io' // 引入Mint-ui // import MintUI from 'mint-ui' // 安装插件 // Vue.use(MintUI); //里面其实做的就是注册所有的全局组件,给Vue.prototype 挂载一些对象,方便实用,组件内的this.xxx就可以使用了 // 引入css // import 'mint-ui/lib/style.css' Vue.use(new VueSocketIO({ debug: true, connection: 'http://127.0.0.1:5000/test' })) /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })