参考了这位作者的服务端配置:https://blog.csdn.net/qq_31967569/article/details/114786587
client配置
引入
cnpm i vue-socket.io -S
cnpm i socket.io-client -S
main.js配置(vue-socket.io的GitHub上有配置示例:https://github.com/MetinSeylan/Vue-Socket.io)
import SocketIO from 'socket.io-client'
import VueSocketIO from 'vue-socket.io'
const options = {
// path: '', /**
*path?: string;
* The path to get our client file from, in the case of the server(从源码复制出来的,没去弄清楚这个path具体作用是干嘛的)
* serving it
* @default '/socket.io'
*/
}
Vue.use(new VueSocketIO({
debug: true, // 调试模式,开启后将在命令台输出蓝色的相关信息
connection: SocketIO('http://127.0.0.1:1111/', options), // 这里的url仅需配置到端口号,我没有配options
vuex: { // 使用Vuex做一些事情时可配置(也暂时没去使用上)
store,
actionPrefix: 'SOCKET_',
mutationPrefix: 'SOCKET_'
}
}))
使用(xxx.vue):可以在组件中的与data同级的sockets直接定义一些socket事件被触发后要做些什么,或者通过this.$socket发送数据等
export default {
name: 'Home',
sockets: {
connect: function () {
console.log('socket connected')
},
reconnect: function () {
console.log('正在重连')
},
customEmit: function (data) {
console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
},
// 客户端接收后台传输的socket事件
message (data) {
console.log('data', data) // 接收的消息
},
reconnect_failed: function (error) {
console.log(error)
},
error: function (error) {
console.log(error)
}
},
data () {
return {
interval: null
}
},
mounted () {
this.interval = setInterval(() => {
this.$socket.emit('login', 'hhh') // 这里是告诉后台触发哪个事件,以及要发送的数据(为了不用更改代码而能从后台不停的触发事件以便于测试功能的正常所以用了定时器)
}, 5000)
}
}
serve端配置(Node.js的一个简单例子):在挂载io的时候配置allowEIO3是为了能兼容低版本v2(说的是socket的版本,我直接install的版本就需要开这个配置,因为默认为false),而配置cors是允许跨域,有更详细的跨域配置请前往官网查看。
const app = require('express')()
const http = require('http').Server(app) // 这里必须绑定在http实例上而不是app上
const io = require('socket.io')(http, { allowEIO3: true, cors: true })
app.get('/index',(req,res)=>{
// console.log(req)
res.send('/index.html')
})
io.on('connect', function(socket){
console.log('a user connected');
});
io.on('connection',(socket)=>{
// console.log(socket)
console.log('a user connected')
socket.on('login', (data) => {
console.log(data);
console.log('登陆了.....');
})
})
http.listen(1111,()=>{
console.log('listening on * :1111')
})
本人遇到的错误:
在vue配置中不明path的作用时配置了path,填了服务端的get路径‘index'后感觉好像通了但触发不了socket事件,这里的path和请求路由的具体作用待研究
在vue配置中去掉path配置,报错400(报跨域就在服务端开cors配置),开启allowEIO3配置后通信正常,事件触发正常,这里就是参考开头的文章的地方