egg-socket.io 的使用
官方文檔看這里 egg-socket.io
接下來的內容其實與文檔里差不多,介意的童鞋略過就好,目前只是簡單的引入,下周往后會寫復雜些的邏輯,在后面的文章會介紹。
貼下目錄結構
1. 下載安裝
cnpm install --save egg-socket.io
2. 開啟插件以及插件配置
開啟插件
// app/config/plugin.js exports.io = { enable: true, package: 'egg-socket.io' };
插件配置
// 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 是 http://socket.io 默認的事件,看這名字就知道是干啥的了,另外一個 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