socket.io 由於使用了 Nginx ,所以需要特別配置


 

首先上代碼

location ^~/socket.io {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_pass http://127.0.0.1:7001;
    }
    location ^~/testsocket.io {
        proxy_set_header X-Real_IP $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X_Forward_For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';

        proxy_pass http://127.0.0.1:7001;
    }

這塊我用的是socket.io 這是nginx的配置,大概意思就是使用HTTP1.1協議,遇到websocket協議就轉發吧,升級到指定協議

服務端代碼

 

server.listen(7001, ( )=>{
    console.log( 'scoket啟動:7001' )
});

 

現在兩人成功通信

 

前端誤區 :

  1 http請求升級

    http://test.com/socket.io/?EIO=3&transport=polling&t=MmeguIG

  2 升級成功

    ws://test.com/socket.io/?EIO=3&transport=websocket&sid=C_h-1N6_v4zSsDDPAAAA

  socket.io 每次連接的前綴 /socket.io 所以nginx才會在轉發層加上 ~/scoket.io 

 

var socket = io();
// Whenever the server emits 'new message', update the chat body
socket.on('server message', function (data) {
    console.log( data )
    //data就是"我連接成功了" socket.emit(
'shoudaomessage', "+++++收到消息+++++"); });

先寫到這,等做出了功能,我再來添加完成版


免責聲明!

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



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