Introduction of WebSocket

WebSocket is a protocol for full duplex communication over a single TCP connection provided by HTML5. WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer. In the WebSocket API, the browser and the server only need to do a handshake, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.

Why can’t the traditional HTTP protocol do what WebSocket does? This is because HTTP is a request-response protocol. The request must be sent from the browser to the server before the server can respond to the request and then send the data to the browser. In other words, the server cannot send data to the browser without the browser asking for it.

Web

Let’s start with express as a basic server.

Create the index.js file

var app = require('express') ();var http = require('http').createServer(app);

app.get('/'.function(req, res){
  res.send('<h1>Hello world</h1>');
});

http.listen(3000.function(){
  console.log('listening on *:3000');
});
Copy the code

Run node index.js, and open http://localhost:3000 in the browser

HTML

Design our home page to achieve a simple chat window.

Modified index. Js

app.get('/'.function(req, res){
  res.sendFile(__dirname + '/index.html');
});
Copy the code

Create index. HTML


      
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: # 000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right:.5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>
Copy the code

Restart the app and refresh the page to see one like the one shown below

Socket.io

The introduction of the socket. IO

npm install --save socket.io

Modified index. Js

var app = require('express') ();var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/'.function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection'.function(socket){
  console.log('an user connected');
});

http.listen(3000.function(){
  console.log('listening on *:3000');
});
Copy the code

Modify index.html by adding the following code under

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
</script>
Copy the code

Restart the application and refresh the page, and you can see the following command line print

Emitting event

When a user enters and submits an input in the chat window, the EMIT event is triggered, and the server listens to the event and reacts accordingly.

Modified index. HTML

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io();
    $('form').submit(function(e){
      e.preventDefault(); // Prevent page reloading
      socket.emit('chat message', $('#m').val());
      $('#m').val(' ');
      return false;
    });
  });
</script>
Copy the code

The server listens for the event and adds the code to the index.js file

io.on('connection'.function(socket){
  socket.on('chat message'.function(msg){
    console.log('message: ' + msg);
  });
});
Copy the code

Display a message

When the server receives the message from user A, the server sends the message again for the client to receive. The client listens to the event and displays the message. In this way, users A, B, and C can receive the message.

Modified index. Js

io.on('connection'.function(socket){
  socket.on('chat message'.function(msg){
    io.emit('chat message', msg);
  });
});
Copy the code

Modify index. HTML to display messages

<script>
  $(function () {
    var socket = io();
    $('form').submit(function(e){
      e.preventDefault(); // prevents page reloading
      socket.emit('chat message', $('#m').val());
      $('#m').val(' ');
      return false;
    });
    socket.on('chat message'.function(msg){$('#messages').append($('<li>').text(msg));
    });
  });
</script>
Copy the code

Restart the application and refresh the page to open multiple browser pages and access localhost:3000 at the same time to experience the effect of a simple chat room.

Set up a nickname

When each user enters, a random number is generated as a nickname for the user, and all users are broadcast that the user enters the chat room. When a user sends a message, the user’s nickname is concatenated.

Modified index. Js

io.on('connection', (socket) => {
  const nickname = 'user' + Math.ceil((Math.random() * 1000))
  socket.broadcast.emit('connection', nickname + ' connected')

  socket.on('chat message', (msg) => {
    io.emit('chat message', nickname + ':' + msg)
  })
})
Copy the code

Modify index.html to listen for connection events

<script>$(() = > {const socket = io()
      $('form').submit((e) = > {
        e.preventDefault()
        socket.emit('chat message', $('#m').val())
        $('#m').val(' ')
        return false
      });
      socket.on('chat message', (msg) => {
        $('#messages').append($('<li>').text(msg))
      })
      socket.on('connection', (msg) => {
        $('#messages').append($('<li>').text(msg))
      })
    });
  </script>
Copy the code

Restart the application and open multiple clients, and you can see the following effect

The resources

IO /get-started…

En.wikipedia.org/wiki/WebSoc…

Liao Xuefeng official website WebSocket

Rookie tutorial WebSocket