vue-socket.io 及 egg-socket.io 的簡單使用

 

egg-socket.io 的使用

官方文檔看這裏 egg-socket.io html

接下來的內容其實與文檔裏差很少,介意的童鞋略過就好,目前只是簡單的引入,下週日後會寫複雜些的邏輯,在後面的文章會介紹。vue

貼下目錄結構node

  

 

1. 下載安裝nginx

cnpm install --save egg-socket.io

 

2. 開啓插件以及插件配置git

開啓插件github

// app/config/plugin.js
exports.io = {
  enable: true,
  package: 'egg-socket.io'
};

插件配置npm

// app/config/config.default.js
// 這裏的 auth 以及 filter 是待會會編寫的兩個中間件,用於不用依據本身的狀況選擇便可
exports.io = {
   namespace: {
       '/': {
           connectionMiddleware: [ 'auth' ],
           packetMiddleware: [ 'filter' ],
       }
   }
};

 

3. 編寫中間件後端

// app/io/middlewware/auth.js
// 這個中間件的做用是提示用戶鏈接與斷開的,鏈接成功的消息發送到客戶端,斷開鏈接的消息在服務端打印
module.exports = app => {
    return function* (next) {
        this.socket.emit('res', 'connected!');
        yield* next;
        console.log('disconnection!');
    };
};

// app/io/middleware/filter.js
// 這個中間件的做用是將接收到的數據再發送給客戶端
module.exports = app => {
    return function* (next) {
        this.socket.emit('res', 'packet received!');
        console.log('packet:', this.packet);
        yield* next;
    };
};

 

4. 編寫控制器瀏覽器

// app/io/controller/chat.js
// 將收到的消息發送給客戶端
module.exports = app => {
  return function* () {
    const self = this;
    const message = this.args[0];
    console.log('chat 控制器打印', message);
    this.socket.emit('res', `Hi! I've got your message: ${message}`);
  };
};

 

5. 編寫路由服務器

// app/router.js
// 這裏表示對於監聽到的 chat 事件,將由 app/io/controller/chat.js 處理
module.exports = app => {
  app.io.of('/').route('chat', app.io.controllers.chat);
};

 

tip:

在業務結束時 發送消息

    // app/controller 中
    async send() {
      const { ctx, app } = this;
      const nsp = app.io.of('/');

      let msg = '{"id":2, "message":666}'

      let data = await JSON.parse(msg)

      // app.io.controllers.chat(msg)
      nsp.emit('chat', data);
      return ctx.body = 'hi, egg';
    }

 

 

vue-socket.io 的使用

1. 下載

cnpm install --save vue-socket.io
cnpm install --save socket.io-client

若是出現頁面顯示不出來,或者出現  TypeError: Cannot call a class as a function

能夠嘗試把依賴 替換成   "vue-socket.io": "^2.1.1-a"

 

2. 鏈接服務器,以及接收服務端消息 

// src/main.js
import VueSocketio from 'vue-socket.io';
import socketio from 'socket.io-client'; Vue.use(VueSocketio, socketio('http://127.0.0.1:7001/')
); new Vue({ el: '#app', router, template: '<App/>', components: { App }, sockets: { connect: function () { console.log('socket connected'); }, res: function (val) { console.log('接收到服務端消息', val); } } });

Vue.use()裏面的 url 是你服務器地址。

connect 是  默認的事件,看這名字就知道是幹啥的了,另一個 res 是自定義的監聽事件,表示監聽服務端發送的名爲 res 的事件。

 

3. 向服務端發送消息

<script>
// ...
methods: {
  sendMessageToServer: function() {
    this.$socket.emit('chat', '111111111111');
  }
}
</script>

這裏咱們使用的事件名爲 chat,因此服務端會將這條消息交給 chat.js(就是上面服務器端項目裏面的文件啦) 這個控制器處理。

 

 

備註

項目部署到生產環境老是會出現各類各樣的錯誤

nodejs+socket.io用nginx反向代理提示400 Bad Request-nginx反向代理nodejs

 

問題描述:在項目中引用Socket.Io,在項目部署後報錯,本地運行不報錯

錯誤緣由:須要在配置文件nginx.conf中配置相關信息

解決方案:

       在nginx文件的location中添加

  

proxy_http_version 1.1;    
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

 

 第一行告訴Nginx在與Node後端通訊時使用HTTP / 1.1,這是WebSockets所必需的。接下來的兩行告訴Nginx響應升級請求,當瀏覽器想要使用WebSocket時,該請求由HTTP啓動。這三行都是必須添加的。

例如:

server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  localhost;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
             proxy_pass  http://localhost:3100;
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection "upgrade";
             proxy_set_header Host $host;
        }
}

 

 

參考連接

 

github

相關文章
相關標籤/搜索