websocket入门
1. python作为服务端代码
1 cat web.py 2 3 from flask import Flask 4 import time 5 from flask_socketio import SocketIO,emit 6 7 app = Flask(__name__) 8 9 socketio = SocketIO() 10 socketio.init_app(app) 11 12 13 """ 14 对socketio进行一些监听设置 15 """ 16 17 @socketio.on('add',namespace='/testnamespace') 18 def give_response(message): 19 20 print(message) 21 emit('response',{'code':'200','msg':'start to process...'}) 22 23 time.sleep(2) 24 emit('response',{'code':'200','msg':'processed'}) 25 26 @socketio.on("get",namespace='/testnamespace') 27 def get_response(message): 28 print(message) 29 30 emit('response',{'code':'200','msg':'start to process...'},namespace="/testnamespace") 31 32 socketio.sleep(2) 33 emit('response',{'code':'200','msg':'processed'},namespace="/testnamespace") 34 35 if __name__ == '__main__': 36 socketio.run(app,debug=True,host='0.0.0.0',port=5000) 37 38 39 ## message 是接受到客户端发送过来的消息 40 ## emit是发送给客户端的消息, response要客户端接受这个event
2. 客户端配置
1 2.1 安装websocket 2 3 cnpm install -S vue-websocket 4 5 2.2 配置 6 7 import VueWebsocket from "vue-websocket" 8 9 Vue.use(VueWebsocket,"ws://127.0.0.1:5000/testnamespace") 10 11 12 <script> 13 export default { 14 15 methods: { 16 add() { 17 // Emit the server side 18 this.$socket.emit("add", { a: 5, b: 3 }); 19 }, 20 21 get() { 22 this.$socket.emit("get", { id: 12 }, (response) => { 23 console.log(response); 24 }); 25 26 // this.$socket.on("response",(response) => { 27 // console.log(response + "ddddd"); 28 // }); 29 } 30 }, 31 32 socket: { 33 // Prefix for event names 34 // prefix: "/counter/", 35 36 // If you set `namespace`, it will create a new socket connection to the namespace instead of `/` 37 // namespace: "/counter", 38 39 events: { 40 41 // Similar as this.$socket.on("changed", (msg) => { ... }); 42 // If you set `prefix` to `/counter/`, the event name will be `/counter/changed` 43 // 44 changed(msg) { 45 console.log("Something changed: " + msg); 46 }, 47 48 response(msg) { #response event和服务端一致 49 console.log(msg); 50 console.log("response: " + msg.msg); 51 } 52 53 /* common socket.io events 54 connect() { 55 console.log("Websocket connected to " + this.$socket.nsp); 56 }, 57 58 disconnect() { 59 console.log("Websocket disconnected from " + this.$socket.nsp); 60 }, 61 62 error(err) { 63 console.error("Websocket error!", err); 64 } 65 */ 66 67 } 68 } 69 }; 70 71 </script>
知人难,相知相惜更难