Moment For Technology

IO and Egg-socket. IO implementation (Simple version)

Posted on June 24, 2022, 1:57 a.m. by Jeffrey Warren
Category: The back-end Tag: node.js

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.

Goal: When the client sends a message to the server, the server can actively push the message to the client

Front-end: vue.js +

Server: node.js + egg.js + egg-socket. IO

If you want to take the new server project and front-end project test, I have a quick build again, is also for websocket learning build, can see from 0 to create a server project with Node.js and interface call

The front-end code

1 the installation package
npm i --save
Copy the code

The version NUMBER I am currently using is:

"": "^ 3.0.10"
Copy the code
2. Introduce in main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false

import VueSocketio from '' // Start with VueSocketio
Vue.use(new VueSocketio({
  debug: true.connection: '',}))// Then register with vue

new Vue({
  render: h=  h(App),
  sockets: { // Mount the socket to vue's this
  // allow each page to use this.$socket to call methods in the plugin
    connect: function () {
    res: function (val) {
      console.log('Received', val);
Copy the code

The corresponding server address is

3. Use it in vUE components
div @click="sendMsg"/divCopy the code
sendMsg() {
  this.$socket.emit('chat'.'MSG sent from client to server')},Copy the code

Remember, webSocket should be automatically enabled whenever you start a VUE project with NPM Run serve

You may find a lot of popular articles, only to find that they are registered in the VUE, and then you find that they are not connected at all, their version number must be installed is NPM install --save, so you don't specify the version number and I'll write it like this, after all, the new package may be more complete

Vue.use(VueSocketio, '');
Copy the code

Server code

See egg.js socket. IO for my directory structure

My project is based on egg.js, which is provided in egg.js

1. The installation package
 npm i --save
Copy the code
2. Register the egg plug-in socket. IO with the egg
  io: {
    enable: true.package: '',},Copy the code

Configuration of 3.

Write to the userConfig object in config/config.default.js

  // socket. IO configuration item
    io: {
      namespace: {
        '/': {
          connectionMiddleware: [ 'auth'].packetMiddleware: [ 'filter'],}}},Copy the code

There are two middleware above, one is AuTH, which mainly reminds users of connection and disconnection. The message of successful connection is sent to the client, and the message of disconnection is printed on the server. The other is filter, which sends the received data to the client


'use strict'
// app/io/middlewware/auth.js
// The function of this middleware is to inform the user of connection and disconnection. The successful connection message is sent to the client, and the disconnection message is printed on the server
module.exports = app=  {
  return function* (next) {
    this.socket.emit('res'.'connected! ')
    yield* next
    console.log('disconnection! ')}}Copy the code


'use strict'
// app/io/middleware/filter.js
// The purpose of this middleware is to send the received data to the client
module.exports = app=  {
  return function* (next) {
    this.socket.emit('res'.'packet received! ')
    yield* next
Copy the code
4 Routes and Files
io.of('/').route('chat', // websocket
Copy the code

Chat here is just a flag specified by the server, and the client sends messages with this flag, which I treat as a key or event name

IO. Controller. Chat is the chat. Js file at the bottom of the IO file at the bottom of the controller file at the bottom of the app file, because the IO is set up as a separate controller

Chat. Js content

'use strict'

module.exports = app=  {
  return function* () {
    const self = this
    const message = this.args[0]
    console.log('Chat Controller print', message)
    this.socket.emit('res'.`Hi! I've got your message: ${message}`)}}Copy the code

The effect

Reference: vue-socket. IO and egg-socket. IO simple use

If you are interested in websocket, you can follow me. Next I should write a code about the chat room that the company is using for its project

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.