移动端h5中使用原生websocket遇到的问题

背景

在一个项目的聊天模块中,前端使用了vue加上h5的原生websocket。

问题

当我在PC端本地测试完毕后,准备完美收场。然而在使用手机连接局域网之后访问该网页,突然发现websocket中的onopen事件失效没有执行,就直接执行了onclose事件。

解决

解决方案有很多中,例如使用一些大神封装好的组件、配合后端使用心跳机制、nginx反向代理等。这里我通过使用nginx做反向代理解决问题。在nginx中代理了后端的websocket连接,使用h5请求websocket时,由nginx做为中间件,向后端发起请求。

代码

    map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }

    upstream websocket {
        server localhost:6666;   # 这里是websocket的访问端口
    }


    server {
     server_name 192.168.1.4;   # 这里是内网端口
     listen 80;
     location /{
         proxy_pass http://websocket;
         proxy_read_timeout 300s;
         proxy_send_timeout 300s;

         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_http_version 1.1;
         proxy_set_header Upgrade $http_upgrade;
         proxy_set_header Connection $connection_upgrade;
     }
}
原创文章 28 获赞 52 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq1123642601/article/details/104174204