The original article is reprinted from liu Yue’s Technology blog v3u.cn/a_id_158

In my previous article, I added webSocket-based real-time communication, active push, chat room and customer service system for Medo Mall (Django2.0.4). I introduced webSocket protocol and how to implement various functions with Django in detail. This time we try to use the socket. IO library and Flask to complete a simple online customer service chat system, and see the difference between the two.

Socket.IO is a Node-based JavaScript framework that encapsulates Websocket, including client JavaScript and Server Node (now also supports Python, Go Lang, etc.). It shields all the low-level details, making top-level calls very simple, and socket. IO has another important benefit. It not only supports WebSocket, but also supports many polling mechanisms and other real-time communication methods, and encapsulates a common interface. These include Adobe Flash Socket, Ajax long polling, Ajax Multipart Streaming, persistent Iframe, JSONP polling, etc. In other words, when socket. IO detects that the current environment does not support WebSocket, it automatically selects the best way to implement real-time network communication, which is much smarter than WebSocket.

We first set up the back-end service

pip install flask  
pip install flask-cors  
pip install flask-socketio
Copy the code

Install Flask local, Cross-domain, and Socketio modules respectively

Upgrade your PIP properly, be careful not to be too low version, below is the demo version number

Flask                 1.1.1  
Flask-Cors            3.0.8  
Flask-SocketIO        4.3.0  
Flask-SQLAlchemy      2.4.1
Copy the code

We then simply write a flask entry to start manage.py

from flask import Flask  
from flask_sqlalchemy import SQLAlchemy  
import pymysql  
from flask import request,jsonify  
from flask_cors import CORS  
from flask_socketio import SocketIO,send,emit  
import urllib.parse  
  
pymysql.install_as_MySQLdb()  
   
app = Flask(__name__)  
  
CORS(app,cors_allowed_origins="*")  
  
socketio = SocketIO(app,cors_allowed_origins=The '*')  
   
@socketio.on('message')  
def handle_message(message):  
    message = urllib.parse.unquote(message)  
    print(message)  
    send(message,broadcast=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=5000)
Copy the code

When instantiating socketio objects, add cors_allowed_origins to set cross-domains. The problem with cross-domains is the browser’s same-origin policy. Cross-domains are best configured on the server side. The advantage of this is that when multiple front-end projects share the same set of microservice interfaces at the same time, there is no need for each front-end project to be configured cross-domain once.

We have written three socketio-based view methods, connect and disconnect, which, as their names suggest, can be captured in time when Clinet initiates a connection or disconnects, while message method is an important method for message communication between the front and back ends.

When sending messages, the method adds a broadcast parameter, which is a feature of socket. IO. It has the effect of broadcasting, and can send messages to clients with different links simultaneously.

The last thing to note is that when the client sends a message, it is best to use urlencode to encode the message, which can solve the Chinese garbled problem. On the server side, it can use urllib.parse.unquote() to decode the message.

Run a command to start the back-end service

python3 manage.py
Copy the code

If the service starts normally on port 5000, there is no back-end problem.

Then we configure the front end (client), the front end uses vue2.0 framework to drive, also need to install socket. IO module

NPM install [email protected]Copy the code

Be sure to specify a version number to install, which is 2.1.0, because the latest version of the dependency will report errors when compiled in the VUe2.0 project

Referenced in the entry file main.js

import VueSocketio from 'vue-socket.io';  
  
Vue.use(VueSocketio,'http://127.0.0.1:5000');
Copy the code

Note That the url of the link is the address and port of the back-end service. Do not add other URL suffixes or namespaces

Create a new index.vue component to simulate user links

<template>  
  <div>  
  
	<div v-for="item in log_list"  
	>  
	{{item}}  
  </div>  
  
	<input v-model="msg" />  
  
	<button @click="send"</button> </div> </template> <script>export default {  
  data () {  
    return {  
	  msg: "", log_list:[]}}, // Register component tag Components :{}, sockets:{connect:function(){  
      console.log('Socket connection successful')  
    },  
    message: function(val){  
	  console.log('return to:+val);  
	this.log_list.push(val);  
	}  
},  
  mounted:function(){  
  
  	  
     
    
},  
  methods:{  
  
	send(){  
	  this.$socket.emit('message',encodeURI("Users."+this.msg));  
    },  
    
  
       
  }  
}  
  
  
</script>  
   
<style>  
  
  
  
</style>
Copy the code

Start the front-end service

npm run dev
Copy the code

Visit http://localhost:8080 and you can see the service success link

At this time, we can try to make another component page item. Vue of background customer service to simulate the scene where users and customer service are chatting on different computers

<template>  
  <div>  
  
	<div v-for="item in log_list"  
	>  
	{{item}}  
  </div>  
  
	<input v-model="msg" />  
  
	<button @click="send"</button> </div> </template> <script>export default {  
  data () {  
    return {  
	  msg: "", log_list:[]}}, // Register component tag Components :{}, sockets:{connect:function(){  
      console.log('Socket connection successful')  
    },  
    message: function(val){  
	  console.log('return to:+val);  
	  this.log_list.push(val);  
	}  
},  
  mounted:function(){  
  
  	  
},  
  methods:{  
  
	send(){  
	  this.$socket.emit('message',encodeURI("Customer service."+this.msg));  
    },  
    
  
       
  }  
}  
  
  
</script>  
   
<style>  
  
  
  
</style>
Copy the code

It works like this:

IO is much more flexible and convenient than Django’s DwebSocket module. If you need to do some active push tasks, you can also use the socket. IO broadcast function, which works the same way as live chat.

The original article is reprinted from liu Yue’s Technology blog v3u.cn/a_id_158