happyChat development series: using websocket.io to realize the development of the big front-end of two-way communication

Posted by rdimaggio on Tue, 07 May 2019 05:50:02 +0200

I. Preface

Leliao is a complete application written by oneself with websocket. Although the function is relatively deficient, it realizes the basic functions of text chat, group chat, private chat, robot chat and so on. Because this has made its own PC terminal, wireless terminal (mobile terminal), and using cordova packaged into an android apk. A big front-end project has been implemented, although there are still some problems with the android side, and bug s are being modified.

2. Introducing the principle of websocket

1. Why do you need websocket?

Because HTTP protocol has a flaw: communication can only be initiated by the client. For example, the only way we want to know about today's weather is when the client makes a request to the server and the server returns the query results. HTTP protocol can not actively push information from server to client.

This one-way request is characterized by the fact that if the server has a continuous state change, it will be very difficult for the client to know. We can only use polling: every once in a while, we send a query to see if the server has new information. The most typical scenario is the chat room.

Polling is inefficient and wastes resources (because you have to keep connecting, or HTTP connections are always open).

2, introduction

websocket features: the server can actively push information to the client, the client can also actively send information to the server, is a real two-way equal dialogue, belongs to the server push technology.

Other features include:

(1) Based on TCP protocol, the implementation of server side is relatively easy.

(2) It has good compatibility with HTTP protocol. The default ports are 80 and 443, and the handshake phase uses HTTP protocol, so it is not easy to shield the handshake, and can pass through various HTTP proxy servers.

(3) Data format is lightweight, performance overhead is small, and communication efficiency is high.

(4) Text or binary data can be sent.

(5) Without homology restriction, the client can communicate with any server.

(6) The protocol identifier is ws (wss if encrypted), and the server address is the URL.

3. Use of websocket.io

1, front-end

In the vue project, in index.html

 <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>
      // const socketWeb = io('http://localhost:3000');
      const socketWeb = io('http://chat.chengxinsong.cn');
      const userInfo = JSON.parse(sessionStorage.getItem("HappyChatUserInfo"))
      if (userInfo) {
        socketWeb.emit('update', userInfo.user_id);
      }
</script>

2, back end

The back end uses koa as the back end

const app = new Koa();

const server = require("http").createServer(app.callback());
const io = require("socket.io")(server);
io.on("connection", socket => {
    const socketId = socket.id;
    /*Sign in*/
    socket.on("login", async userId => {
        await socketModel.saveUserSocketId(userId, socketId);
    });
    // Update soketId
    socket.on("update", async userId => {
        await socketModel.saveUserSocketId(userId, socketId);
    });
    //Private chat
    socket.on("sendPrivateMsg", async data => {
        const arr = await socketModel.getUserSocketId(data.to_user);
        const RowDataPacket = arr[0];
        const socketid = JSON.parse(JSON.stringify(RowDataPacket)).socketid;
        io.to(socketid).emit("getPrivateMsg", data);
    });
    // Group chat
    socket.on("sendGroupMsg", async data => {
        io.sockets.emit("getGroupMsg", data);
    });

    //Friend Request
    socket.on("sendRequest", async data => {
        console.log("sendRequest", data);
        const arr = await socketModel.getUserSocketId(data.to_user);
        const RowDataPacket = arr[0];
        const socketid = JSON.parse(JSON.stringify(RowDataPacket)).socketid;
        console.log('To whom? socketid',socketid)
        io.to(socketid).emit("getresponse", data);
    });
    socket.on("disconnect", data => {
        console.log("disconnect", data);
    });
});

IV. Brief Introduction and Functions

Happy Chat, an application of Happy Chat, supports PC and wireless and Android APP.

(1) Address of PC and wireless terminals: http://chat.chengxinsong.cn

(2) Download Android APP Address: There are still some minor problems to be solved, and then release the address.

Version v 1.0.0

- 1. Support registered users and email activation users;
- 2. Support landing
 - 3. Support robot chat;
- 4. Support and friends, one-to-one chat;
- 5. Support group creation, group addition and one-to-many chat.
- 6. Support deleting friends and quitting groups
 - 7. Supporting Personal Information Editing
 - 8. Support for adding friends'notes
 - 9. Supporting Text Sending in Chat
 - 10. Support browsers: Chrome, Firefox, Safari, IE9 and above; 
  • Version v 1.1.0

    • 1. Supporting Picture Sending in Chat
    • 2. Supporting Emotional Sending in Chat
    • To be continued

Operational screenshots

Wait...

6. Front-end and back-end source code

Front-end code: https://github.com/saucxs/hap...

Backend code: https://github.com/saucxs/hap...

Seven, last

Welcome fork and star, ask questions

Topics: Front-end socket JSON Android github