Front and back end interaction problems

Single delivery of HTTP

The most basic protocol, usually the front end sends to the background, there are get, POST and so on, but now there are a lot of other packages on the front end, axios and so on. The downside is that it can only be the front end making requests to the back end.

Two-way information transmission

To use this because of the recent projects needs to be informed to the background to the front end of the message, which is a before and after the interaction process, in the process of the past we mainly use HTTP requests for the front-end to the back-end to such interaction is single, the message when we need the background to the front, can use the websocket. Of course, brute force cracking is always possible, so technically there are usually three ways to do it: short polling and long polling webSockets

Brute force cracking method: long and short polling

Brute force is always the most familiar method – the client send the HTTP request to the server a while back to the background, time interval length determines the number of polling, however, because every time to send the HTTP request message head could be more than content, so the disadvantages of polling there will be a waste of bandwidth, but simple point is that the pressure on it to implement without any technology.

Websocket: True duplex implementation

Compared to brute force cracking, websocket is more intelligent and elegant 🤯 (of course, is in the premise of making, not to make, all kinds of strange errors more let a person from the closed

The mechanism of the websocket

Websocket first uses HTTP to make the connection. After the connection is complete, the service is handed over to WebSocket to manage, and then the permanent connection is established.

Websocket js native implementation

The native implementation of WebSocket is relatively simple: python is used to write the back-end code, js is used to write the front code (JS is es6, this is based on the React framework, extracted from the middle).

import asyncio
import websockets

Receive the client message and process it
async def recv_msg(websocket) :
    while True:
        recv_text = await websocket.recv()
        response_text = f"your submit context: {recv_text}"
        await websocket.send(response_text)

# server side master logic
# websocket and path are passed automatically when the function is called back
async def main_logic(websocket, path) :
    await recv_msg(websocket)

Change the IP address to your local IP address
start_server = websockets.serve(main_logic, 'localhost'.5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Copy the code
// Open a Web socket
const ws = new WebSocket("ws://localhost:5678");

// After the connection is established
ws.onopen=() = >
{
	console.log("Successful connection")}// After receiving a message from the server, the connection will be monitored until the connection is established
ws.onmessage=(e) = > 
{ 
    const received_msg = e.data;
    console.log("Received a message:"+received_msg);
}

// Pass data to the server
ws.send("msg")

// After the connection is closed
ws.onclose =() = >
{ 
    console.log("Connection closed..."); 
}
Copy the code

This implementation is very simple and simple, and for the front end, all the use is combined on this.

Implementation of websocket: based on socket.io

IO/socket. IO /

How to use socket. IO in python Flask? The backend project is based on python flask framework, so it is set to be used in flask framework. flask sockets flask socketio

Flask Sockets: Simple wrappers for websockets, used only in the WebSocket phase, not if webSockets are not available

Flask Socketio: This is a more complete one: WebSockets are used when they are available, long polling is used when they are not.

Therefore, we finally decided to use Flaks Socketio, and then socketio-client was used in the front section, and the use of background can refer to the online writing method

Install react-socket-io NPM install react-socket-io NPM install react-socket-io

// How to use it

// Import, using es6 method
import io from 'socket.io-client'

// Connect to the background http://ip:port/namespace
const socket = io("http://192.168.6.140:6888/test_conn")

Server_response is not fixed, it is paired with the back end
// If the front end is listening on 'server_response', the back end socketio.emit('server_response',' MSG ')
socket.on('server_response'.(data) = >{
    console.log(data)
    Socketio. on('event',namespace='/test_conn')
    socket.emit('event'."message")})Copy the code

Tread pit record —- error record

  • Cannot read property ‘sid’ of undefined

    • The preceding segment can receive sid information sent by the background. However, an error occurs during socktio resolution and the SID information cannot be obtained

    • // The first message retrieved from the network
      0{"sid":"NWUwZWY4NzBiYjk1OQ=="."upgrades": []."pingInterval":44000."pingTimeout":36000}
      
      
      // Network information flow
      server----------------------------client
      ----0{sid,upgrades,pinginterval... } -- -- -- -- >< -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- {40} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- > {40} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > {40} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - >Copy the code

      Import IO from ‘socket. IO -client’, do not require(‘socket. IO -client’)

  • Error: http1.1 400 or http1.1 404

    • Background socketio should have one

      socketio = SocketIO(app, async_mode=async_mode,cors_allowed_origins=The '*')
      Copy the code