Tag Archives: WebSocket 

Pycharm WebSocket Error: Error: Connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

Problem description

Pycharm encountered SSL error while running websocket

Error: Connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

Problem-solving

Since I use Anaconda environment in pycharm, I need to configure it in the environment corresponding to anaconda

python -m certifi

Get certificate path

conda config --set ssl_verify <your-path>

Save the certificate path so that websocket can be opened normally

Websocket Front-end Call Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">Send message</button>
<hr/>
<button onclick="closeWebSocket()">Close WebSocket connection</button>
<hr/>
<div id="message"></div>
</body>
<script>
var websocket = null;
// determine if the current browser supports WebSocket
if ('WebSocket' in window) {
	websocket = new WebSocket("ws://localhost:8080/wsServer");
}
else {
	alert('The current browser does not support websocket')
}

// Callback method for connection error
websocket.onerror = function () {
	setMessageInnerHTML("An error occurred with the WebSocket connection");
};

// Callback method for successful connection establishment
websocket.onopen = function () {
	setMessageInnerHTML("WebSocket connection successful");
}

// Callback method for received message
websocket.onmessage = function (event) {
	setMessageInnerHTML(event.data);
}

// Callback method for closing the connection
websocket.onclose = function () {
	setMessageInnerHTML("WebSocket connection closed");
}

// Listen to the window close event and actively close the websocket connection when the window is closed to prevent the window from being closed before the connection is broken, which will throw an exception on the server side.
window.onbeforeunload = function () {
	closeWebSocket();
}
 
// Display the message on the web page
function setMessageInnerHTML(innerHTML) {
	document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
 
//Close the WebSocket connection
function closeWebSocket() {
	websocket.close();
}
 
//Send a message

function send() {
var message = document.getElementById('text').value;
	websocket.send(message);
}
</script>

</html>

[Solved] jumpserver nginx Error: Connect websocket server error

After installation, the jumpserver selects a custom port, and the HTTP port 80 is changed to 88. After forwarding through nginx, remember to set the upgrade of nginx, otherwise it will prompt: connect websocket server error

Nginx is configured as follows:

##Jump
server {
listen 80;
server_name jump.xxxxxx.cn;

location/{
proxy_pass   http://127.0.0.1:88;
        proxy_http_version      1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
}
}

This will not prompt an error

[Solved] Error during WebSocket handshake Unexpected response code 404

Problem Description: the websocket project was well deployed before. When it was transplanted to the domain name specified by the government cloud SLB, an error occurred:
error during websocket handshake unexpected response code 404

Solution

1. Configure nginx

In any case, configure nginx:
proxy_http_version 1.1;
proxy_set_header Connection "upgrade";
proxy_set_header Upgrade $http_upgrade;

location /xxx{
    proxy_pass http://127.0.0.1:7071/xxx;
    proxy_redirect    off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_http_version 1.1;
    proxy_set_header Connection "upgrade";
    proxy_set_header Upgrade $http_upgrade;
    
    proxy_connect_timeout 60s;
    proxy_read_timeout 7200s;
    proxy_send_timeout 600s;
    
    # 再不行的话就把下面的设置试一下
    #proxy_set_header Upgrade websocket;
    #proxy_pass_request_headers on;
    #access_log off;
    #proxy_buffering off;
    
}

2. Websocket configuration

We use springboot, and all configurations cannot be less

import com.fh.websocket.session.MySpringConfigurator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * enable WebSocket support
 */
@Configuration
public class WebSocketConfig {

	@Bean
	public ServerEndpointExporter serverEndpointExporter() {
		return new ServerEndpointExporter();
	}

	@Bean
	public MySpringConfigurator mySpringConfigurator() {
		return new MySpringConfigurator();
	}
}

3. Websocketserver needs to add a parameterless constructor

This is a pit, and it is normal to deploy to another
transplanting will not work in the past.

[Solved] Websocket Error: WebSocket is already in CLOSING or CLOSED state

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

Gateway forwards weboskct with an error ClassCastException

    usage environment: the springcloud gateway forwards an error message to the websocket. Error message content:

    15:30:38.092 [http-nio-9999-exec-1] ERROR c.m.g.e.GlobalErrorWebExceptionHandler - [handle,38] - org.apache.catalina.connector.ResponseFacade cannot be cast to reactor.netty.http.server.HttpServerResponse
    java.lang.ClassCastException: org.apache.catalina.connector.ResponseFacade cannot be cast to reactor.netty.http.server.HttpServerResponse
    	at org.springframework.web.reactive.socket.server.upgrade.ReactorNettyRequestUpgradeStrategy.getNativeResponse(ReactorNettyRequestUpgradeStrategy.java:182)
    	Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
    Error has been observed at the following site(s):
    	|_ checkpoint ⇢ org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
    	|_ checkpoint ⇢ org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
    	|_ checkpoint ⇢ HTTP GET "/sys/websocket/1" [ExceptionHandlingWebHandler]
    Stack trace:
    		at org.springframework.web.reactive.socket.server.upgrade.ReactorNettyRequestUpgradeStrategy.getNativeResponse(ReactorNettyRequestUpgradeStrategy.java:182)
    		at org.springframework.web.reactive.socket.server.upgrade.ReactorNettyRequestUpgradeStrategy.upgrade(ReactorNettyRequestUpgradeStrategy.java:162)
    		at org.springframework.web.reactive.socket.server.support.HandshakeWebSocketService.lambda$handleRequest$1(HandshakeWebSocketService.java:235)
    		at reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:151)
    		at reactor.core.publisher.MonoFlatMap.subscribeOrReturn(MonoFlatMap.java:53)
    		at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:57)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    		at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    		at reactor.core.publisher.Mono.subscribe(Mono.java:4252)
    		at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.drain(MonoIgnoreThen.java:172)
    		at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:56)
    		at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    		at com.alibaba.csp.sentinel.adapter.reactor.MonoSentinelOperator.subscribe(MonoSentinelOperator.java:40)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    		at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64)
    		at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    
      cause of error: dependency conflict
      the Tomcat servlet of springboot is used in the request and the Tomcat of gateway netty is used in the response, so the type conversion exception is caused. Solution: modify the gateway POM file:
      delete or exclude the following dependencies

      <dependency>
      	<groupId>javax.servlet</groupId>
      	<artifactId>javax.servlet-api</artifactId>
      </dependency>
       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
       <dependency>
      	<groupId>javax.servlet</groupId>
      	<artifactId>jstl</artifactId>
      </dependency>
      <dependency>
      	<groupId>org.apache.tomcat.embed</groupId>
      	<artifactId>tomcat-embed-jasper</artifactId>
      </dependency>
      

[Solved] Vue Error: Uncaught TypeError: Cannot read property ‘getters‘ of undefined

The error is as follows:

Cause analysis

I wanted to add a public data source in the modules folder under the store directory to cache data for sharing by multiple components, but I haven’t finished writing it yet. Therefore, this error is reported.

Solution:

Write the basic structure completely. As follows:
the directory is: store/modules/xxx. JS

Novices continue to grope for themselves

Nginx manager jupyter notebook v1.0.0 http websocket

v1.0.0

Environment introduction

1、 The virtual machine on this machine. There is jupyter in the virtual machine

2、 Jupyter notebook web server is an online editor

3、 A proxy server on this machine, such as nginx

Configuration steps

1、 Virtual machine

Start the virtual machine

2、 Jupyter

Set the root directory of the file
sudo GEDIT (VIM) ~ /. Jupyter/jupyter_ notebook_ config.py

c.NotebookApp.notebook_dir = '/path/to/jupyter'

sudo gedit(vim)~/.jupyter/jupyter notebook config.py

c.NotebookApp.allow_origin = '*' # allow cors

3、 Nginx

Start nginx configuration nginx.conf excerpt

# Actual tcp/websocket server address
    upstream jupyter_url {
        server virtual machine ip:8888;
    }

    server {
        listen       8000;
        server_name  localhost;

        charset utf-8;

      location/{
          proxy_pass http://jupyter_url;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade; 
          proxy_set_header Connection "upgrade";
      }
	}

Test effect

Visit: nginxip: 8000

Flutter SocketException: OS Error: No route to host, errno = 113, address = XXX

Or flutter   WebSocketChannelException: SocketException: OS Error: No route to host, errno = 113, address = XX

This type of access problem,

1. First of all, whether the port on the server side is open or not, MacOS or windows, please do it yourself

2. The problems encountered here, I will explain my situation. First of all, the test I did belongs to the type of LAN, and I know that my server IP and real mobile phone, including web page test, are all in the same network segment. For example, 192.168.1.xx to 192.168.1.250. There is no problem with the access of the extension computer, but the mobile phone has this problem, The IP of the mobile phone is also in the same segment with the server we tested, but why is the problem of not finding the host mentioned above?

Finally, we found that the mobile phone is linked in the 5g band of the router, which may be due to the IP isolation between 5g band and other IP when the router is set up, resulting in mutual inaccessibility

It’s OK to enter 2.4G

WebSocket failed: Error during WebSocket handshake: Unexpected response code: 400

The front-end and back-end architecture are separated, the development environment is normal, and the errors reported when deploying to the line are as follows:

Websocket error: websocket failed: error during websocket Handshake: unexpected response code: 400

It is obvious that the configuration of nginx does not support the reverse proxy of websocket, so the search and troubleshooting results are as follows:

The most important of them are the three lines

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

The first line tells nginx to use HTTP/1.1 communication protocol, which websoket must use. The second and third lines tell nginx to respond to the HTTP upgrade request when it wants to use websocket. Here, HTTP and websocket reverse proxy coexist, just a protocol upgrade

Supplement:

	server {
	        listen       80;
	        server_name  school.godotdotdot.com;
	        charset utf-8;
	        
			proxy_http_version 1.1; 
			proxy_set_header Upgrade $http_upgrade;
			proxy_set_header Connection "upgrade";
	

	        location/{
	            proxy_pass http://127.0.0.1:3000;
	            proxy_set_header Host $host;
	            proxy_set_header X-Real-IP $remote_addr;
	            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	            proxy_connect_timeout 60;
	           proxy_read_timeout 600;
	           proxy_send_timeout 600;
	        }

	        error_page   500 502 503 504  /50x.html;
	        location = /50x.html {
	            root   html;
	        }
	 }

failed: Error during WebSocket handshake: Unexpected response code: 200

This problem is often encountered when webSocket connections are made. A comparison between previous projects and current WebSockets shows that there is an additional blocking function. Therefore, it is generally found that the reason lies in the interceptor to see whether the webSocket request address is blocked by the interceptor.

Websocket code 200 error

WebSocket connection to ‘XXX’ fails: Error during WebSocket handshake: Unexpected Response code 200
This problem is mainly the problem of background, the front-end address access is yes
in my own configuration used in the project of the security framework of Shiro, because no open access permissions so appeared the error
it is good to open the access here

if it is not the problem can look for the background does not open access what
if the address was wrong will directly at 404 mistakes, instead of 200