Vue.js如何使用Socket.IO的示例代码

如题所述



在很多需求业务中,都需要浏览器和服务器实时通信来实现功能,比如:扫码登录(扫码后,手机确认登录,PC网页完成登录并跳转)、订单语言提醒等,这些都是建立在两端实时通信的基础上的。对前端而言,来实现浏览器和服务器实时通信,最好的选择就是Socket.IO库,能够快速的实现两端实时通信功能。



1、什么是 Socket.IO?

Socket.IO 是一个WebSocket库,可以在浏览器和服务器之间实现实时,双向和基于事件的通信。它包括:Node.js服务器库、浏览器的Javascript客户端库。它会自动根据浏览器从WebSocket、AJAX长轮询、Iframe流等等各种方式中选择最佳的方式来实现网络实时应用,非常方便和人性化,而且支持的浏览器最低达IE5.5

2、Socket.IO 主要特点



(1)、支持浏览器/Nodejs环境 (2)、支持双向通信 (3)、API简单易用 (4)、支持二进制传输 (5)、减少传输数据量

3、Vue.js 中 Socket.IO的使用



(1)客户端

npm install vue-socket.io --save
main.js添加下列代码

import VueSocketIO from 'vue-socket.io'

Vue.use(new VueSocketIO({
debug: true,
// 服务器端地址
connection: 'http://localhost:3000',
vuex: {
}
}))
发送消息和监听消息

//发送信息给服务端
this.$socket.emit('login',{
username: 'username',
password: 'password'
});
//接收服务端的信息
this.sockets.subscribe('relogin', (data) => {
console.log(data)
})
(2)服务端



服务端,我们基于express搭建node服务器。

npm install --save express
npm install --save socket.io
index.js文件

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.send('<h1>你好web秀</h1>');
});

io.on('connection',function(socket) {
//接收数据
socket.on('login', function (obj) {
console.log(obj.username);
// 发送数据
socket.emit('relogin', {
msg: `你好${obj.username}`,
code: 200
});
});
});

http.listen(3000, function(){
console.log('listening on *:3000');
});
然后启动服务端服务

node index.js
客户端即可查看效果。

4、Socket.IO有哪些事件



io.on('connect', onConnect);
function onConnect(socket){
// 发送给当前客户端
socket.emit(
'hello',
'can you hear me?',
1,
2,
'abc'
);
// 发送给所有客户端,除了发送者
socket.broadcast.emit(
'broadcast',
'hello friends!'
);
// 发送给同在 'game' 房间的所有客户端,除了发送者
socket.to('game').emit(
'nice game',
"let's play a game"
);
// 发送给同在 'game1' 或 'game2' 房间的所有客户端,除了发送者
socket.to('game1').to('game2').emit(
'nice game',
"let's play a game (too)"
);
// 发送给同在 'game' 房间的所有客户端,包括发送者
io.in('game').emit(
'big-announcement',
'the game will start soon'
);
// 发送给同在 'myNamespace' 命名空间下的所有客户端,包括发送者
io.of('myNamespace').emit(
'bigger-announcement',
'the tournament will start soon'
);
// 发送给指定 socketid 的客户端(私密消息)
socket.to(<socketid>).emit(
'hey',
'I just met you'
);
// 包含回执的消息
socket.emit(
'question',
'do you think so?',
function (answer) {}
);
// 不压缩,直接发送
socket.compress(false).emit(
'uncompressed',
"that's rough"
);
// 如果客户端还不能接收消息,那么消息可能丢失
socket.volatile.emit(
'maybe',
'do you really need it?'
);
// 发送给当前 node 实例下的所有客户端(在使用多个 node 实例的情况下)
io.local.emit(
'hi',
'my lovely babies'
);
};
温馨提示:答案为网友推荐,仅供参考