Problem 1.

Recently, I have been studying the communication between the front and back ends of WebSocket, which requires the front end to input data and the back end to loop back the data corresponding to the front end

As shown in the following figure, the front-end input is S2, and the back-end socket returns the corresponding data

While (true){… Get the data, call send(), return the front end… }

The next time I send S1, the back end cannot receive my request parameters this time because it is still executing the last task, so the data cannot be updated to S1 data

2. To deal with

After thinking about it, I wrote the method of receiving the message and processing the data back to the front end to the thread, and then controlled the closure of the thread with a flag bit

So that when I execute next time close the last thread, open a new thread processing, each request does not affect each other, there will not be blocked phenomenon, and still the kind of infinite loop, ha ha ha

This problem involves the use of multithreaded flag bit out of the while loop knowledge

Method 3.

3.1 the vue front-end * * * *

The specific method is recorded in detail in my blog “Spring Boot Series: Vue+Sping Boot +WebSocket implementation before and after the message push”, here only deal with the problem

3.2 Java backend

For webSocket, see “Spring Boot Series: Vue+Sping Boot +WebSocket”.

3.3 a multithreaded

import com.trgis.util.UdpServerSocket; import com.trgis.vo.SocketVO; import java.io.IOException; import java.util.ArrayList; import static java.lang.Thread.sleep; Public class MyRunnable implements Runnable {/** * implements Runnable; Public volatile Boolean flag = true; // Use volatile to ensure visibility, change flags in one place, and read new values from main memory everywhere, instead of using cache. public String message; public MyRunnable(String message) { this.message =message; } public void run() {system.out.println ("第" + thread.currentThread ().getid ()+ "Thread created "); try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } int i=0; While (flag) {system.out.println (thread.currentthread ().getid ()+"message "+message+i++); } } public static void main(String[] arg) throws InterruptedException { MyRunnable runnable = new MyRunnable("1"); For (int I = 0; i < 1; i++) { Thread thread=new Thread(runnable,i+" "); thread.start(); } thread.sleep (2000L); System. The out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- "); // Change the exit flag so that the thread terminates runnable.flag = false; }}Copy the code