写了个简单的DEMO,不懂操作的同学可以看看,安装 vue 就不多说了,官方文档很详细
#安装服务器端
npm install --save socket.io
npm install --save express
npm install --save request
npm install --save redis
#安装客户端
npm install --save socket.io-client
#安装VUE库
npm install --save vue-socket.io
在vue的 main.js 里写上
//与服务端链接
import VueSocketio from 'vue-socket.io';
import socketio from 'socket.io-client'
Vue.use(VueSocketio, socketio('ws://127.0.0.1:3000',{
query: 'token=1234567'
}));
编辑 App.vue,编写事件方法
<script>
export default {
name: 'app',
sockets:{
//跳转登陆界面
auth_to_login:function(){
this.$router.push({ name: 'login'});
},
//跳转到首页
auth_to_index:function(){
this.$router.push({ name: 'Index'});
}
}
}
</script>
服务端端代码
let socketIo = require('socket.io');
let express = require('express');
let request = require('request');
let redis = require('redis');
let redisClient = redis.createClient;
let httpPort = 3000;
let channelId = 1
let app = express();
app.get('/',function(req,res){
res.send('启动成功:' + httpPort);
});
//连接redis
let cache = redisClient({ port: 6379, host: '127.0.0.1' });
let server = require('http').createServer(app);
let io = socketIo(server);
io.on('connection',function(socket){
console.log('有客户端连接' + socket.id);
//取得token
let token = socket.handshake.query.token;
//根据token看是否有效登陆状态
if (!token){
console.log('没有授权');
socket.emit('auth_to_login');
return false;
}else{
#通过取得redis cache判断
cache.get(token, function (err, response) {
if (!response){
console.log('账号过期');
#通知客户端
socket.emit('auth_to_login');
//当然也可以使用 disconnect 断开链接,如果是单页应用,断开后记得要重新建立连接
//socket.on('disconnect', function() {});
}else{
#通过API判断
let result = request({
url: 'http://xx.com/user/check',
method: "POST",
json: true,
headers: {
"content-type": "application/json",
"charset":"UTF-8",
},
body: {token:token}
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
body = JSON.stringify(body)
result =JSON.parse(body)
if (result.code == 0){
#通知客户端
socket.emit('auth_to_index');
}
}
});
}
});
return false;
}
});
server.listen(httpPort); //用server连接
启动socket服务器
执行 node app.js
网友评论