When the front-end project communicates with the back-end Java websocket for a long time, sometimes the browser will report an error
WebSocket is already in CLOSING or CLOSED state.
This problem may be caused by the data length passed by websocket being greater than 8192 After websocket establishes a connection, the length of JSON passed should be & lt= 8192, otherwise an error will be reported Websocket is already in closing or closed state.
1. At this point, we can add some code in web.xml to limit the parameter length limit in websocket.
# Limit WebSocket pass data size to 50M
<context-param>
<param-name>org.apache.tomcat.websocket.textBufferSize</param-name>
<param-value>5242800</param-value>
</context-param>
<context-param>
<param-name>org.apache.tomcat.websocket.binaryBufferSize</param-name>
<param-value>5242800</param-value>
</context-param>
After adding the above code, you can modify the size and length of the transfer parameters of websocket, which is limited to 50m.
2. The above method is not available for the springboot project because there is no web.xml file in the project directory. At this time, we can put the following code into the springboot project under the context directory of the project (or create a new code class or block at will)
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.util.WebAppRootListener;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
/**
* Add WebSocket pass data size limit of 50M
*/
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class WebSocketConfig implements ServletContextInitializer {
//Configure websocket transfer size, 50M
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addListener(WebAppRootListener.class);
servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize","52428800");
servletContext.setInitParameter("org.apache.tomcat.websocket.binaryBufferSize","52428800");
}
}
The above code can solve the problem of websocket is already in closing or closed state
You can successfully modify the size limit of websocket transmission data to 50m.
Note: a problem was found during use. If the above configuration is started with the built-in Tomcat in springboot, there is no problem, but the operation using the external Tomcat after war does not take effect. Finally, it is found that the problem is due to the external Tomcat version. The problem version is tomcat8.0.xx, but there is no problem using tomcat8.5.xx