这篇文章主要介绍了Vue.js使用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('<h2>你好web秀</h2>');
});
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'
);
};
感谢你能够认真阅读完这篇文章,希望小编分享的“Vue.js使用Socket.IO的方法”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。