在vue中如何使用WebSocket 以及nginx代理如何配置WebSocket


WebSocket

WebSocket是一種網絡傳輸協議,可在單個TCP連接上進行全雙工通信。瀏覽器和服務器只需要完成一次握手,兩者之間就可以創建持久性的連接,並進行雙向數據傳輸。

瀏覽器支持情況

image

現代瀏覽器基本都支持WebSocket

在vue中的使用

data(){
	return {
		socket:null
	}
},
mounted () {
            window.onbeforeunload = function () {
                this.close()
            }
			this.initSocket()
        },
        destroyed () {
            // 銷毀組件時關閉socket
            this.close()
        },
        methods: {
            initSocket: function () {
                if(typeof(WebSocket) === "undefined"){
                    alert("您的瀏覽器不支持socket")
                }else{
                    // 實例化socket
                    let path = `ws://10.0.2.15:8800/ws/${id}`;
                    this.socket = new WebSocket(path)
                    this.socket.onopen = this.open
                    this.socket.onerror = this.error
                    this.socket.onmessage = this.getMessage
              this.socket.onclose = this.close
                }
            },
            open () {  //連接成功調用send發送數據
                console.log("socket連接成功");
                let msg = {"test":"hellow"};
                this.send(JSON.stringify(msg));
            },
            error () {  //連接失敗重連
                console.log("socket連接錯誤")
                this.initSocket()
            },
            getMessage (msg) {  // 接收數據
                const redata = JSON.parse(msg.data);
           console.log("socket接收數據",redata);
            },
            send (Data) {
                this.socket.send(Data)
            },
            close () {
                console.log("socket關閉")
            },

詳情請查看這里

nginx配置websocket

平時很多項目都是使用nginx部署上線的,那么如果項目里使用了websocket,相對應的也需要去配置nginx。

server {
        listen       8099;     #端口號
        server_name  http:10.0.1.55;  #服務器地址或綁定域名

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location /{
            root   E:/www/;   #項目文件夾
            index  index.html index.htm;
        }

        location /api/ {
            proxy_pass http://10.0.2.15:8800/;#應用服務器HTTP地址
        }
		#websocket代理配置如下
        location /ws/ {
            proxy_pass http://10.0.2.15:8800;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_read_timeout 36000s; #10小時未傳輸數據則關閉連接
        }
	}

默認情況下,如果代理服務器在60秒內未傳輸任何數據,則連接將關閉。可以使用proxy_read_timeout指令來增加此超時時間 。或者,可以將代理服務器配置為定期發送WebSocket ping幀以重置超時並檢查連接是否仍然有效。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM