vue + koa2 + socket.io 實現(xiàn)簡單聊天室

vue 使用 vue-socket.io,nodejs 使用 socket.io 實現(xiàn)簡單聊天室
vue 前端頁面
首先 npm install vue-socket.io -S 下載組件

// main.js
import scoket from "vue-socket.io"; // 引入組件
Vue.use(new scoket({
  debug: true, // 開啟提示
  connection: url,  // 后臺服務(wù)地址
}))
// speak.vue
mounted(){
  this.$socket.emit("connection",1);
},
methods: {
  sendMessage(val) {
    this.$socket.emit("chatmessage", {name:val,value:this.value});
    this.value = "";
  },
},
sockets: { // 名字不能改,服務(wù)觸發(fā)方法的列表 
  connect() {
    //與socket.io連接后回調(diào)
      console.log("socket connected");
  },
  // user 名字,與服務(wù)端保持一致,data 后臺返回數(shù)據(jù)
  user(data) {
    // 執(zhí)行的操作
    this.message.splice(this.message, 0, data);
  }
}
----------------------------- node.js -------------------------------------
import koa from 'koa'
const app = new koa()
const server = app.listen(4000);
const io = require('socket.io').listen(server);
io.sockets.on('connection', (socket) => {
    console.log('連接成功', { id: socket.id })
    socket.on('chatmessage', (msg) => {
        io.sockets.connected[socket.id].emit('user', msg.value); // 指定發(fā)送
        socket.emit('user', msg.value); // 廣播
    });
    socket.on('disconnect', () => { // 關(guān)閉鏈接的時候會執(zhí)行
        console.log('user disconnected');
    });
});

大概就是這樣子吧,不太完善,不過可以特別簡單的用

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容