--------- WebSocket distal heart note

  WebSocket

  HTML5 WebSocket is a protocol provided by the start of full-duplex communication over a single TCP connection.

  WebSocket enables exchange of data between the client and the server easier, allowing the server actively push data to the client. In the WebSocket API, the browser and the server only needs to complete a handshake, you can directly create a persistent connection between the two, and two-way data transmission.

  In the WebSocket API, the browser and the server just need to do a handshake of action, and then, on the formation of a fast-track between the browser and the server. You can transfer data directly between each other.

  Now, many sites in order to achieve push technology, the technology used is Ajax polling. Polling is in a specific time interval (e.g., every 1 second), issues an HTTP request to the server by the browser, and returns the latest data to the client browser by the server. This traditional model brings obvious disadvantage that the browser requires constant request to the server, however, HTTP requests may contain a long head, which truly effective data may only be a small part, obviously this will waste a lot of bandwidth resources.

HTML5 WebSocket protocol definition, better able to save server resources and bandwidth, and can be more real-time communication.

 


 

  WebSocket server to allow the initiative to push data to the client, and the browser and the server requires only one handshake can establish a data transmission channel of each other. Now commonly use terms such as real-time chat.

  Now most of the sites will also use  Ajax polling    technology to push data to achieve, and this technology means that at a specific time interval, requesting data from the server by the browser, the server responds to the request to the browser and push them up on the page on this model a great waste a lot of bandwidth resources, because the browser needs to continue to send requests to the server.

    The WebSocket can better conserve server resources and bandwidth, and can be more real-time communication.


 

  By making simple WebSocket Case :: synchronous chat page

  This project is only in the same domain, tested under the same ip, node build server.

  1.npm init -y

  2.npm intall

  3.npm moment reference address https://momentjs.com/   

  4.npm install --save socket.io Reference Site https://socket.io/get-started/chat/

  

  App.js server code portions:

var Express = the require ( 'Express' );
 // introduced Express 
var App = Express ();
 // instance of an object 
var Moment = the require ( 'Moment' );
 // time of introduction plug, the first instruction execution npm moment 
var path = the require ( 'path' );
 // introduced into the core module node path 
var http = the require ( 'http' ) .createServer (App);
 // introduced http server module creation method 
app.use (express.static (path.resolve (__ dirname , 'public /' )));
 // intermediate functions express.static access static resource directory. 
var IO = the require ( 'Socket.IO' ) (HTTP); 

//1. on behalf of that event listener (Event name: connection, when the client connects, connection callback function immediately executed) 
// parameter socket 2. Representatives of the callback function is the current client to the client can take the initiative to push through this socket information; 

io.on ( 'Connection', function (socket) { 

    / * listens to join an event * / 
    socket.on ( 'JOINUS', function (the Data) { 
        console.log (the Data); 

        // own information broadcast all out 
        // allUsers.forEach (); 
        // socket.emit ( 'Guangbo', Data); 
        // built broadcast 
        io.emit ( 'Guangbo' , Data);
                // io.emit broadcasted 
    }); 

    / * listening chat event * / 
    socket.on ( 'sendData',function (Data) {
         // Nickname, Content, added August 23, 2019 16:46:28 
        // data.time new new = a Date (); // Moment 
        . data.time = Moment () the format ( 'YYYY- DD-HH the mM: mm: SS ' ); 
        
        io.emit ( ' msgGuangbo ' , Data); 

    }) 

}); 


// build websocket server, no separate structures themselves, by means of http protocol 

// server listens to port 3000 
http.listen ( 3000, function () { 
  the console.log ( 'Listening oN *: 3000' ); 
});     

// run the code used to open the server node app.js
// localhost input in the browser: 3000; open

 

  html code portions index.html

</head>
<body>
  <div class="i-body">
    <h1>请输入你的昵称:</h1>
    <form id="nicknameForm">
      <input type="text" id='nickname'>
    </form>
  </div>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/2.0.1/jquery.js"></script>
<Script of the type = "text / JavaScript" > 
  $ ( " #nicknameForm " ) .submit ( function (Event) { 
    event.preventDefault (); // prevent the default event 
    var the Nickname = $ ( " #nickname " ) .val (). TRIM ();
     IF ( ! nickname) { 
      Alert ( ' enter nickname! ' );
       return ; 
    } 

    localStorage.setItem ( ' nickname ' , nickname); 
    the location.href =  ' /room.html';
  });
</script>

 

Chat HTML code portion

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>迷你聊天室</title>
  <link rel="stylesheet" href="./style/style.css">
</head>
<body>
  <header class="c-header">
    <h1>迷你聊天室</h1>
    <div class="c-user"><img src="./imgs/1.jpg" title=""></div>
  </header>
  <div class="c-body">
    <div class="c-main">
      <ul class="c-list">
      </ul>
      <div class="c-xxx"></div>
      <div class="c-chat">
        <img class="c-avatar2" src="./imgs/1.jpg" alt="">
        <input class="c-input" type="text" id="chatContent">
        <button class="c-btn" id="chatBtn">发送</button>
      </div>
    </div>
  </div>
</body > 
</ HTML > 

< Script the src = "https://cdn.bootcss.com/jquery/2.0.1/jquery.js" > </ Script > 
< Script the src = "https://cdn.bootcss.com /socket.io/2.2.0/socket.io.js " > </ Script > 


< Script type =" text / JavaScript " > 
  // when a new person is added to the chat room, the person is sent to the current server, server broadcast to all people. 

  var Nickname = localStorage.getItem ( ' Nickname ' );
   IF ( ! Nickname) { 
    Alert ( '');

    location.href = '/index.html';

  }

  var url = 'http://localhost:3000';
  socket = io(url);

  socket.on('connect', function () {
    console.log( 'connect' );
  });

  socket.emit('joinUs', {nickname});


  socket.on('guangbo', function (data) {
    console.log('广播', data );
    var _html = `<li class="c-item">
          <div class="c-join-info">【${data.nickname}】加入聊天室</div>
        </li>`;
    $(".c-list").append( _html );
  })

  socket.on('msgGuangbo', function (data) {

    console.log('msgGuangbo', data );
    var _html = ``;
    if( data.nickname == nickname ){
      // my-item 自己发送的增加底纹
      _html = `<li class="c-item my-item">
          <img class="c-avatar" src="./imgs/5.jpg" title=""> 
          <div class="c-box">
            <div class="c-info">
              <div class="c-name">${data.nickname}  ${data.time}</div>
            </div>
            <div class="c-content">${data.content}</div>
          </div>
        </li>`;
    }else{
      _html = `<li class="c-item">
          <img class="c-avatar" src="./imgs/5.jpg" title=""> 
          <div class="c-box">
            <div class="c-info">
              <div class="c-name">${data.nickname}  ${data.time}</div>
            </div>
            <div class="c-content">${data.content}</div>
          </div>
        </Li> `; 
    } 

    $ ( " .c-List " ) .append (_html); 

  }) 

  $ ( " #chatBtn " ) .click ( function (Event) {
     var Content = $ ( " #chatContent " ) .val ( ) .trim ();
     IF ( ! content) { 
      Alert ( ' enter chat! ' );
       return ; 
    } 
    $ ( " #chatContent " ) .val ( '' );
     // send message 
    socket.emit('sendData', {content, nickname});

  });

</script>

 

Socket Reference Site https://www.w3cschool.cn/socket/socket-1olq2egc.html

 

 

Code is mainly to provide ideas, the principles are the same! !

 

 

 

 

 

 

 

    

Guess you like

Origin www.cnblogs.com/hudunyu/p/11402272.html