vue-socket.io 和 flask_socketio使用

2018-07-13  本文已影响0人  moodi

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文件中

<script>
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)
    }
  },
}
</script>

各种命令行使用:https://rootopen.com

上一篇下一篇

猜你喜欢

热点阅读