vue-socketio

1.配置,vue-cli裡面(因爲我之前用2.9几版本的發現引入vue-socket.io編譯會報錯,所以直接用vue-cli版本了)main.js文件

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import VueSocketio from 'vue-socket.io';
Vue.config.productionTip = false
const url = `http://127.0.0.1:3000`;
Vue.use(new VueSocketio({
  debug: true,
  connection: (url),
}))


new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

2.服務端(nodejs)

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection',function(socket) {
  console.log("1,listening on *:3000connction")
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
  //接收数据
  socket.on('login', function (obj) {                
      console.log("login",obj.username);
      // 发送数据
      socket.emit('relogin', {
        msg: `你好relogin,${obj.username}`,
        code: 200
      });
      socket.emit('reflog2',{
        msg:'第二次reflog',
        code:200
      })  
  });
  socket.on('join',function(obj){
    console.log(`${obj.username}加入房間${obj.groupId}成功`)
    socket.emit('joinSuccess',{
      msg:`${obj.username}加入房間${obj.groupId}成功`,
      code:200
    })
  })
  setInterval(() => {
    let date = new Date();
    socket.emit('currentTime',{
      data:date,
      code:200
    })
  }, 1000);

  socket.emit('test', {
    msg: `test測試信息`,
    code: 200
  }); 

});
 
http.listen(3000, function(){
  console.log('listening on *:3000');
});

3.前端代碼




後台傳給前台的數據,前台無法在sockets里監聽到

socketio會默認下載3.0.9版本(2020.05.20),不知道我是不是遺漏了什麼,這裡回退到了3.0.7版本就可以監聽到sockets裡面的信息了

附上github地址:
https://github.com/thbor/socketo-test

你可能感兴趣的:(前端,vue-socketio)