1. 程式人生 > >socket.io實現多種連線的做法

socket.io實現多種連線的做法

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
    #ul1 {width:400px; height:300px; border:1px solid black; overflow:auto;}
    #ul1 li.me {color:green}
    .err_box {width:100%; height:20px; line-height: 20px; text-align:center; color:red; display:none}
    </style>
    <script src="http://localhost:8080/socket.io/socket.io.js" charset="utf-8"></script>
    <script>
    let sock=io.connect('ws://localhost:8080/');

    sock.on('connect', ()=>{
      document.getElementsByClassName('err_box')[0].style.display='none';
    });
    sock.on('disconnect', ()=>{
      document.getElementsByClassName('err_box')[0].style.display='block';
    });

    //聊天室
    window.onload=function (){
      let oTxt=document.getElementById('txt1');
      let oBtn=document.getElementById('btn1');
      let oUl=document.getElementById('ul1');

      oBtn.onclick=function (){
        sock.emit('msg', oTxt.value);

        let oLi=document.createElement('li');
        oLi.innerHTML=oTxt.value;
        oLi.className='me';

        oTxt.value='';

        oUl.appendChild(oLi);
      };

      sock.on('msg', str=>{
        let oLi=document.createElement('li');

        oLi.innerHTML=str;
        oUl.appendChild(oLi);
      });
    };
    </script>
  </head>
  <body>
    <div class="err_box">
      無法連線到伺服器,請檢查網路
    </div>
    <ul id="ul1"></ul>
    <textarea rows="4" cols="60" id="txt1"></textarea>
    <input type="button" value="傳送" id="btn1">
  </body>
</html>
/*
  socket.io 多種連線的情況
    socket服務監聽連線
      1.將每一個新建立的連線的套接字物件新增到陣列中,
      2.套接字監聽斷開連線事件,已經斷開,就從陣列中移除套接字; sock.on('disconnect')
      3.套接字監聽事件,迴圈陣列,將資訊傳送給非本套接字的其他套接字;
*/
const http=require('http');
const io=require('socket.io');

let httpServer=http.createServer((req, res)=>{

});
httpServer.listen(8080);

//
let wsServer=io.listen(httpServer);

let aSock=[];
wsServer.on('connection', sock=>{
  aSock.push(sock);

  //斷開連線
  sock.on('disconnect', ()=>{
    let n=aSock.indexOf(sock);

    if(n!=-1){
      aSock.splice(n, 1);
    }
  });

  sock.on('msg', str=>{
    aSock.forEach(s=>{
      if(s!=sock){
        s.emit('msg', str);
      }
    });
  });
});

setInterval(function (){
  console.log(aSock.length);
}, 500);