@玛酷猫8 年前
11/3
10:46
公司rails项目中通过Faye来实现一个简单的好友聊天互动的功能,移动端需要开发简易的教师上课点名的小功能,想想正好可以利用Faye服务来实现,具体逻辑很简单,在课程页面,教师点击点名模块,设置密钥后进入点名页面,通过Faye发布该课程点名信息,学生接收到点名信息后在页面上显示签到按钮,学生点击签到按钮输入密钥,通过Faye服务传递到教师点名页面上,时时反馈签到情况,最后教师通过关闭按钮结束签到并通过Faye告知所有学生,学生页面隐藏签到按钮。
逻辑理顺了,页面搭建完毕,加入Faye犯难了,官方文档只是简单写了下浏览器端如何使用,引入Faye服务端js,然后可以使用subscribe和publish来发布和接受了。在Ionic3项目里面就傻眼了,第一步引入js就不知道咋搞了,网上翻资料,绝大部分都是使用ionic 1.x的资料,度娘里面居然还掺杂一大堆王菲的搜索页面。。。谷歌研究了半天,参考了一篇关于ionic3部署socket.io的文章,终于搞定。
首先还是安装Faye组件
npm install faye --save
新建一个服务provider,初始化同时把相关的推送接收用法写进去
import { Injectable } from '@angular/core';
import * as Faye from 'faye'
@Injectable()
export class FayeService {
clientUrl: string;
data: any;
client: any;
constructor() {
this.clientUrl = 'https://your website/faye';
this.data = null;
this.client = new Faye.Client(this.clientUrl)
}
subscript(callback:any, channelName:string){
this.client.subscribe('/' + channelName, function (data) {
callback(data);
// console.log('receiced data:'+data);
})
}
publish(channelName:string, data:any){
let publication = this.client.publish('/' + channelName, data);
publication.then(function() {
}, function(error) {
console.log('There was a problem: ' + error.message);
});
}
}
最后在app.module.ts中引入这个provider并声明下就可以在项目中使用了。
此外还有一点,由于项目的browser版和接口都启用的ssl,直接使用http://your website:8080/faye 会报错,提示在ssl下访问非ssl存在安全问题balabala之类的,这个需要在nginx中设置端口转发。
在nginx的接口配置文件中添加faye的upstream
upstream faye-socket{
server 127.0.0.1:8080;
}
接着在配置443的server下面添加转发规则
location /faye {
proxy_pass http://faye-socket;
proxy_http_version 1.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_cache_bypass $http_upgrade;
}
保存后重新加载nginx配置即可。
nginx -s reload
