1, the preface

IO encapsulates WebSocket and AJAX polling, forming a set of APIS, shielding details and compatibility problems, and realizing bi-directional data communication across browsers and devices. WebSocket is a two-way communication protocol. WebSocket and HTTP are based on TCP

2. Function and effect

  • Log in, log out
  • Multi-user chat
  • One-on-one chat
  • Results the following

3. Directory structure

  

4. Node services

The socket. IO service needs to rely on the HTTP service. By installing Express, create an HTTP service and then install socket. IO

npm i socket.io express -S
Copy the code

Access the page by visiting localhost:3000

// app.js
const app = require("express") ();const server = require("http").Server(app);
const io = require("socket.io")(server);

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

server.listen("3000".function () {
  console.log("Service starts at 3000");
});
Copy the code
Socket. IO API used by the server
const io = require("socket.io")(server);
/ / connection socket. IO
io.on("connect".(socket) = > {
    // socket.on("receive", params); // Socket. receive
    socket.emit("receive",params);
    // socket.on('send') emit("send", params); send
    socket.on("send",params);
    // IO. Emit ("all") represents broadcast and sends a message to each client
    io.emit("all",params)
}) 
Copy the code

5. Use of client socket

The client uses the EMIT of socket. IO to send messages and on to receive messages, using the same API as the server’s index.html

// The client needs to import packages
<script src="/socket.io/socket.io.js"></script>
<script>
    / / use
    let socket = io("http://localhost:3000");
    // 1. Wait for the notification from the server
    socket.on("notify".(username) = > {
      message(`${username}In! `.1);
    });
     // 2. Send messages to the server
    function send() {
      if(! info.value) message("Please enter a message".0);
      socket.emit("message", people);
    }
</script>
Copy the code

6. User login and list display process

  • The client logs in and sends the account name to the server through sock.emit
  • The server sends a message to the client through socket.emit. The login succeeds, and broadcasts the message to all clients through IO
  • The server saves the user information to the user and broadcasts it to the client
  • The client shows the data it gets

7, one to one dialogue function

IO. To (socketId). To (socketId). Emit (‘my Message ‘)

Server code

  // Send a message to someone
  socket.on("say to someone".(myId, userId, msg) = > {
    let { sockedId, username } = users.find((el) = > el.sockedId === myId);
    io.to(myId).to(userId).emit("my message", username, msg);
  });
Copy the code

Client code

  // 4. Press Enter to send the message to a single person
  function clickEnter(e) {
    let myId = socket.id;
    let userId = event.path[0].getAttribute("sockedId");
    let msg = event.path[0].value;
    var evt = window.event || e;
    if (evt.keyCode == 13) {
      event.path[0].value = "";
      socket.emit("say to someone", myId, userId, msg); }}// 5. Display the received message
  socket.on("my message".(username, msg) = > {
    let date = new Date().toLocaleString();
    message(`${username}: ${msg}---------${date}`.3);
  });
Copy the code

8. Complete code

1. Client

Simple chat room

Current User List



    Account:




    2. The server

    const app = require("express") ();const server = require("http").Server(app);
    const io = require("socket.io")(server);
    server.listen("8080".function () {
      console.log("Service starts at 3000");
    });
    app.get("/".function (req, res, next) {
      res.sendFile(__dirname + "/index.html");
    });
    let users = []; // Records information about all current users
    / / the connection
    io.on("connect".(socket) = > {
      // Login processing
      socket.on("login".(username, id) = > {
        users.push({
          username: username,
          sockedId: id,
        });
        socket.username = username;
        // Push login succeeded
        socket.emit("loginSuccess");
        // Broadcast event IO. Emi join notification
        io.emit("notify", username);
        io.emit("updateUserList", users);
      });
      // Exit the connection
      const disconnect = () = > {
        if (socket.username) io.emit("loginOut", socket.username);
        users = users.filter((item) = >item.username ! == socket.username); socket.username ="";
        io.emit("updateUserList", users, socket.username);
      };
      // Listen for user disconnection and user exit
      socket.on("disconnect", disconnect);
      socket.on("loginOut", disconnect);
      // Message processing
      socket.on("message".(people) = > {
        let { username, message } = people;
        io.emit("recevied", username, message);
      });
      // Disconnect the connection
      socket.on("error".(reason) = > {
        console.log(reason + "Error occurred");
      });
      // Send a message to someone
      socket.on("say to someone".(myId, userId, msg) = > {
        let { sockedId, username } = users.find((el) = > el.sockedId === myId);
        io.to(myId).to(userId).emit("my message", username, msg);
      });
    });
    Copy the code

    9, reference

    Documents:Socket. IO/docs/v3 / ind…
    Websocket + NodeJSJuejin. Cn/post / 684490…

    Making address:Github.com/s2265681/ro…