Why do

In my work, I often saw others using and contacting Websocket, but I couldn’t use it in my own work, so I thought of doing a personal project to learn Websocket, happened to see a music chat room project created with Websocket, so I developed such a music chat room hall from scratch. I would like to record a personal project and share it with you.

  • Project preview address music chat hall

Differences between WebSocket and HTTP

In our daily development, the most contact is HTTP protocol, HTTP protocol is used in the application layer protocol, he is based on TCP protocol, HTTP protocol to establish a link must have three handshakes to send information. In this scenario, the server is passive, he can not go to the client operation and communication, can only wait for the client initiative, this scenario is also a lot of, in daily development, part of the time need to use polling can highlight the disadvantages of this communication in some scenarios, so websocket emerged.

WebSocket he is in order to solve the client to initiate multiple HTTP requests to the server resource browser must go through a long time of rotation and training problems, he realized multiplexing, he is full duplex communication. Under the webSocket protocol, the client and the browser can send messages simultaneously. With WebSocket, the server does not have to send a message to the browser after the browser sends a request. At this time the server has the initiative to send when you can send information to the server. And the message does not have to be part of the message with the HEAD to communicate with HTTP long links, this way, not only reduces the server pressure. And the information is also reduced some of the redundant information.

Technology selection

Often when we are developing something by ourselves, we spend less time writing code, and more time thinking about how to do the project, what technology to use, how to assemble it, and so on. As long as we think about these questions well, we can start writing very quickly.

My personal habit has always been to write the front and back end separately, so the first idea is to divide the project into two projects at the front and back end. The front end chooses vUE, the technology stack currently used by the company, and the back end chooses Node, which can be used by each front end quickly. Meanwhile, compared with Websocket, I chose socket-IO with more complete encapsulation. There’s not much difference. Generally speaking, socket-io is the encapsulation of Websocket, but it is not completely correct. Socket. IO encapsulates WebSocket, Polling mechanism and other real-time communication methods into a common interface, and its daily use is much the same.

  • The front end

    1. Using a front-end frameworkvueBasic front-end development
    2. usesocket-io-clientalternativewebsocketDuplex communication
    3. Using a suite ofvue-socket.io-extendedforsocket-ioinvueA package integration, convenient in the development of more convenient use
  • The back-end

    1. usenodeThe frameworknestjsBack-end development (because it was used beforeexpress.koaSuch as developing personal projects, company projectshapiPersonal feelings, different frames do have different feelings,express.koaThis kind of framework does not help you forcibly restrict your development, there is no unified specification, because different people have different development interests, and the definition of Nest isA progressive Node.js framework for building efficient, reliable, and scalable server-side applications; Don’t ask me why, they say graphics drive traffic.So I came here to try itnestjsFor this development)
    2. Databases are used most personallymysql
    3. The orm to use thenestjsForm a complete set oftypeorm. (Personal feelingtypeormNothing you used beforesequelizeEasy to use), of course, as the front end, itself may not know the back end, this is all personal preferences and decided.
    4. As a music chat room, of course, can not leave the music library,The source of the song is through the crawler to obtain xx music website to achieve

General idea of project

To create a music chat room, shallow just see, need two things, music, chat function, to achieve these two functions, we are divided order, first to achieve chat, on the basis of chat to achieve music.

  1. In order to achieve the chat function, the front end initiates a connection request, and the back end processes the connection, records the connected user, and retains the basic information of the individual for distribution to other users who enter the chat room.
  2. Permission validation for the project is still usedjsonwebtokenBut the idea here is a little bit different from what we do everyday
  3. When we connect successfully, we will start to play the music, and if we want all the songs to be synchronized, then it means that the control of the song playback needs to be done by the back end rather than the front end, so how to control the music playback is also a problem
  4. At the same time, what functions do we need to achieve? Chat and send text messages, publish feelings, send pictures, copy and paste send pictures, request songs, cut songs, top songs, and so on, we come to achieve it one by one

Realize the function

1. Check the permissions of the front and back ends

In our daily use of front and back end interaction, we will carry token in the request header, and this operation, we generally use AXIOS request interception for global operation, so how do we operate socket? First, we still need token for verification, so login is necessary. We log in and we get the token carried in the socket request. In the front-end project, we usually only maintain one socket instance, so let’s see what we need to initialize.

Socketio initialization parameters are basically like this. What’s the use of this kit? In fact, when we use the suite, first of all, $socket is mounted on the prototype of Vue. Second, we can define sockets that are the same level as methods and data when the component is used. The server and client communicate with each other through events. Each side triggers different events to tell the other side what to do. There is a problem here, where to add our token. The official document did not find a specific method. First of all, we know that the token here cannot be added globally in AXIos, so we need to deal with it by ourselves.

First of all, when we use the socket, we must discard the traditional HTTP method, start a new concept, here, is to initialize is created, when we at the time of initialization, the user can not login, again how can have token, so it is clear that the token of injection timing must be connected before and after landing, So we can skip initialization and go to the connection phase.

Frequent authentication by the server will consume unnecessary performance. The front end will first judge that there is no token to force the user to log in before connecting. How to connect?

We put the token before connecting this $socket. Client. IO. Opts. Query, can also be placed into the request header, personal needs, both can, we just in order to in the process of request connection, carry on the token, then we can control the incoming parameters, Of course, you can also carry more parameters than token, see if necessary, and then the server can retrieve the token in the request query for verification. In this way, we are free to control the connection timing and parameters, and the server validation is no different from normal HTTP validation without rejecting the connection.

In socket, we don’t need to carry token in every request, we only need to carry token in the connection this time, after the subsequent connection passes, a fixed connection ID will be generated,cliend.id, which is the only credential information of the connection between the two parties, and we also communicate with you through this, so our permission is completed here.

Two, chat room message communication exchange

As a chat room, the most basic function is to chat, we how to chat, we said that in front of the socket communication is the response to a variety of actual events, simple to understand is that we define some method, will be in the process of the two sides to send events trigger, how to send the event, the client and the server is slightly different

  • The clientthis.$socket.client.emit('CustomEvent', data)Here is the client sending an event calledCustomEventAnd carried itdataAfter sending the request, the server will execute the definitionCustomEventMethod, while receiving the data data. For example, in the following figure, a message is received

  • The service side the same but different, why say so, because, on the client side, we are one to one, our goal is only the service side, so we can only send events to the server, but not on the server, there are multiple clients connect him, so he is more than one, he for many people the rune, therefore, he faces the incident scene is divided into three categories,

    1. Sends event notifications like one of the currently connected clients
    2. Like sending messages to everyone except the currently connected user
    3. Send messages to all users that contain the currently connected client

    It’s easy to understand that we can’t send all messages to everyone, we need to distribute messages to different people, and with this concept you can quickly understand

Iii. Basic interaction process

Generally speaking, our daily chat content will exist in the DB project source code has been bound to a database, here I use mysql, these are similar, we do not need to pay too much attention to, let’s roughly analyze a user to send a message after what needs to do.

  1. When user A connects to A room, we first give the user the initial information of the room. What information does A basic chat room have?

    1. History User chat messages
    2. Room information, room announcement, other room custom Settings
    3. A list of all current online users, including basic information about the user, such as gender, signature, and so on
    4. The song information, the song that is currently playing, how many seconds has it been playing, and when has it been playing? [More on that later]
  2. The user sends a message after entering the room, the server receives the message, the first thing you need to save the message in the db to store the historical records, and then put this message notification to all people, and then all clients will receive to have a new message to inform, will let the new messages pushed into the current list, so that no matter who send message, All you have to do is add to the array.

  3. This is the basic flow of a chat

Of course, simple chat does not only have text messages, we also have expressions, pictures, or in wechat, we add text and small expressions. How to achieve this, we will analyze one by one

  1. For us, a small expression is actually just a small icon or picture, so when we choose, we actually choose a picture, which is generally presented as follows

  1. And what we found is that when you click on the emoticon it turns into this format, actually if you look at the previous emoticonQQYou’ll find that a lot of them are/ laughLike this format, he’s actually converting the path of the image into a key value that passes when it’s sent outv-htmlOr some other way to recompile it into oneimgThe hashtag is enough to achieve the effect of such a small expression and text together, and send it out as follows

  1. Expression we need to send the second package, then by the same token, the expression package for us is a picture, a picture to address, the difference is that expression package we don’t need him to stay in the input field, it is more simple, direct click on the package, will send a picture link, and to distinguish between news, only need to give a message plus a type, for exampleText Text type.Img image type.Notice Indicates the type of message notificationThis makes it easy to distinguish styles by rendering them with different types, as shown in the following image

  1. And the third thing is, if the user wants to send their own image message how do they do that? Well, we know that images are sent by pasting them or sending a file, essentially sending a file, how do you do that?inputOne of the events is the paste event@pasteAmong theme.target.fileCan get paste image information, and then through the file upload interface to upload the files to a remote, through the interface to get the pictures of a return address, the address of the image to the server completes the custom image is charged to send, so video, also is in the same way, of course, is that clear?

4. Music function

As music chat rooms, in addition to chat, the second is the function of music, of course, for the h5, h5 is a video or audio, that everybody knows you don’t have to say, we only need to address can play SRC into resources, is very simple, but of course we don’t just for the sake of simple songs, we want to realize a person, The ability for everyone to order songs together and then play them together in order, so everyone enters the chat room and hears the same song at the same time, the client only needs two things for this function,

  • The front-end thinking

    1. Know what song is playing and what the source address of the song is.
    2. The current playing song to which second, the user will enter from the current everyone together this time start to play, synchronous play
    3. The general process is: enter the room or room information state, current song, start playing time of song, load the song, jump to the current playing time and start playing
    4. Note that currently, due to browser limitations, music cannot be played automaticallyautopalayIt will not take effect, and can only be played if there is interaction with the user. Therefore, before entering the room, there is a popup window for the user to confirm, so as to realize the function of playing when entering the room.
  • The back-end idea

    1. First of all, we need song resources, we need to use the crawler, in the initialization stage to get a part of the song as, when no one clicks on the song when the random music, this part of the source code initialization stage has detailed comments, depending on personal preferences are willing to initialize the load of music.
    2. Play songs of the time when there is a server control automatic switch songs too, so the service side need to know what time the switch songs, guarantee the songs have been at the same time, so we need to launch start playing music, how to operate, is a random song from the database, and then began to record, record the current song, And then the time of the current song, the resource address of the current song and so on, when the user enters the room, it pushes it to the user, but how does the user know how many seconds it is when they enter the room, so we need to record a timestamp when we get the song from the databasetimespaceAfter the user enters the room, the entry time minus the recorded timestamp is the song playing time, and the song is played from this time
    3. So when to cut the song, automatically cut the song of course need to switch ah, when the song finished playing? It is the time of a song, and we know the time of the song when we get the information of the song. As long as we set a timer, the method of cutting the song after so many seconds is good. At the same time, we update the timestamp again when switching, and we will realize an automatic cutting song function
    4. And, of course, we also need to user and so operation, how to achieve this, song search also need to use the crawler, search for songs, search to the song, song and so will the current user id and sent to the server, the server will record who ordered what song, of course, we also need to have the first division, so we need to maintain aThe queue, will be in order to add song users’ songs, at this time, automatic song cutting will not go to the database to read, the general process is to viewThe queueThere are no songs that users click on, not in the databaserandomGet one, if there is a queue to get the first song, and then cut the song, and then remove the queue of songs, to achieve the automatic playback of songs.
    5. So someone’s song is very ugly to do, or the user wants to remove their own song, are very simple, get the song ID and user information, remove from the queue, the general idea is like this, there are a lot of details, there are a lot of points that can be optimized, look forward to everyone to mentionissuesPoint it out!

Five, the summary

Holding the attitude of learning to learn may be slow, holding the attitude of interest to learn will get twice the result with half the effort, the learning as entertainment, playing strange upgrade will be very interesting, a small personal project to share with you, inadequate place welcome everyone to put forward, learn and progress together.

Personal blog

Here is my personal blog, welcome each friend message exchange friend chain message remarks according to the home page format can blog address