注意:

首先确定开启websocket服务,一般websocket和服务地址是同一个

如果nginx是在docker上配置的要确定是否映射了端口号

因为是使用的反向代理,所以web访问的地址不是websocket的服务地址


在Nginx中配置websocket
http {
    keepalive_timeout  65;
    #下面这个可以不配置
    map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}
   # 通过ip地址和端口号进行反代理
   
    upstream websocket {
    server 192.168.50.131:21852;
}
server {
location /ws/ {                                                                                                                                                                                                                                 
    proxy_pass http://websocket;                                                   
    # WebScoket Support                    
    proxy_http_version 1.1;                                                              
    proxy_set_header Upgrade $http_upgrade;              
    proxy_set_header Connection "upgrade";                                                                                                                                                             
} 
}
}

HTML5页面用来验证websocketshi
不要使用postman来验证,会产生误导,我遇到的问题是一般websocket是get请求,使用postman需要传入页面,传入页面需要post请求
<script>
    var ws = new WebSocket("ws://192.168.50.131:31890/eduplatform/notify/push?token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTkwNTk5MzAsImlhdCI6MTU5NjQ2NzkzMCwiaXNzIjoibG9naW5fdG9rZW4iLCJsaWNlbnNlIjp0cnVlLCJsb2dpbnRpbWUiOiIxNTk2NDY3OTMwIiwicm9sZSI6InRlYWNoZXIiLCJ1c2VyaWQiOiJlMzE1NGJjNjY1OTIifQ.kcrCIJ4UYXBHiMcxPwjAjVjQHxOL2DNG-5yBq9QWxE60s2mLfonHmFiVKAAtyM9qqUxgXzuRPUDwVetSi9VbUf-gdySofU0HBQR5PJhSxLzEyjoW7WMmQdL-6IQ6lwIQYNtp0diW_bKXAueLFm673oaawfXASvYNPjHRUIGzdJVg60LtXrza0goQRsxsU-mKY8rhQkn-7QAn6oki9jq62Klheuwo_kX0qwI-rfRyU_uTqI4V9-HlwGu4Wf29m2uIBw-mhuAfFm-oGmm4zZ-uydCBKe8bO_ateYNrOJXYKb8ETLEjmoFGkZXhhxnXxbh_GrHggEM3ZmC7BNNgwXwh9EC_VsEhQ1CdaRW8GcxAYAen2s7ghxeVAQQbbMXO_o7BfoawQXUoTXCSlGhbuO3afm1GuI5TaujAIhfm1WShJgcYvgBhLealJD_HuK8fWxQqw44Z5ziHlSKlT_Y8E4IqiA0p_68vpvGqlqNj7vLnd-LcVDIXOiWv26m-g-TZYN_NmmYz84QF8DsNxApYTD7ZiDQ5lwAO0-1R5LLmWvAhuCQnlx0cHMYouFtT4rGWjLvXOw1z20nWtak8f0KlHmFpaTkGkDCpdV5vWhl1DGzjZSyg_mTzt26BTr8XdIv1FGoRsaVZY0xbvMqpKviMnGpD_JXwIjUC9pKJs4D7xWeij9s");

    ws.onopen = function(evt) {
        console.log("Connection open ...");
        ws.send("Hello WebSockets!");
    };
</script>
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐