python socketio 性能_vue-socket.io 和 flask_socketio使用

栾烨华
2023-12-01

python 服务端代码

需要先安装flask 和 flask_socketio

pip install flask

pip install flask_socketio

# -*- coding: utf-8 -*-

from flask import Flask

from flask_socketio import SocketIO,send,emit

app = Flask(__name__)

app.config['SECRET_KEY'] = 'secret!'

socketio = SocketIO(app)

@socketio.on('message')

def handle_message(message):

print 'message'

send(message)

# emit('my response')

@socketio.on('json')

def handle_json(json):

print 'json'

# send(json, json=True)

@socketio.on('my event')

def handle_my_custom_event(json):

print json

# emit('my response')

# send({'data': 'Connected'},json=True)

@socketio.on('connect', namespace='/chat')

def test_connect():

emit('my response', {'data': 'Connected'})

@socketio.on('disconnect', namespace='/chat')

def test_disconnect():

print('Client disconnected')

if __name__ == '__main__':

socketio.run(app,debug=True,host='0.0.0.0',port=9999)

vue客户端使用

需要先安装 vue-socket.io

npm install vue-socket.io

mian.js加入

import VueSocketio from 'vue-socket.io'

Vue.use(VueSocketio,'https://192.168.2.66:9999')

在.vue文件中

export default {

name: 'Index',

data () {

return {

}

},

methods: {

send(){

console.log('1111111');

this.$socket.emit('message','1111111111');

},

},

sockets:{

connect: function(){

console.log('socket connected')

},

message: function(val){

console.log('返回:'+val)

}

},

}

 类似资料: