socket.io

作者: 秋天de童话 | 来源:发表于2019-01-17 23:25 被阅读6次

    server.js

    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);
    
    

    1.html

    <!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

          本文链接:https://www.haomeiwen.com/subject/jvnwdqtx.html