公司最近要重写聊天模块,因为之前使用的环信开始收费,成本太大,负担不起。于是,新的即时通讯模块就由公司唯一的iOS程序员---->我去负责开发(小公司程序员伤不起555)。
经过九曲十八弯的调研和测试,我发现市场上存在这种情况,完善点的第三方比如环信和容联,收费都很贵,不完善的比如bmob,极光目前是免费,但是很难保证以后不会像环信一样以后收费。于是,痛定思痛,决定用免费的开源第三方FaceBook的SocketRocket 来尝试自己实现即时通讯技术,后台的话就用node.js搭建基本的聊天环境(刚好我懂点node基础,哈哈)。
SocketRocket的具体介绍......(此处省略一万个字,要想知道,请百度)
废话不多说搞起来!
第一步:安装SocketRocket到xcode
github地址:SocketRocket
或者直接:pod 'SocketRocket'
安装即可
-------------------------------------------------
第二步:利用node.js搭建后台服务支持
这里要用到npm的第三方库nodejs-websocket,
npm的地址:nodejs-websocket
或者你也可以在终端输入:npm i nodejs-websocket
安装完后新建一个js文件,并添加如下代码:
var ws = require("nodejs-websocket")
var server = ws.createServer(function (conn) {
console.log("New connection")
conn.on("text", function (str) {
console.log("Received "+str)
conn.sendText(str.toUpperCase()+"")
})
conn.on("close", function (code, reason) {
console.log("Connection closed")
})
}).listen(8001)
console.log("websocket连接完毕")
保存为socketServer.js,
在终端运行:node socketServer.js
-------------------------------------------------
第三步:编写xcode代码
3.1 引包
#import <SocketRocket/SRWebSocket.h>
3.2添加代理
<SRWebSocketDelegate>
3.3 暴露属性
@property(strong,nonatomic)SRWebSocket *webSocket;
3.4 添加各种方法:
- (void)viewWillAppear:(BOOL)animated{
[self Reconnect];
}
- (void)Reconnect{
self.webSocket.delegate = nil;
[self.webSocket close];
self.webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.2.67:8001/"]]];
self.webSocket.delegate = self;
self.title = @"Opening Connection...";
[self.webSocket open];
}- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
self.webSocket.delegate = nil;
[self.webSocket close];
self.webSocket = nil;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.webSocket send:@"1111"];
}#pragma mark - SRWebSocketDelegate
- (void)webSocketDidOpen:(SRWebSocket *)webSocket{
NSLog(@"Websocket Connected");
self.title = @"Connected!";
}- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
NSLog(@":( Websocket Failed With Error %@", error);
self.title = @"Connection Failed! (see logs)";
self.webSocket = nil;
}- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
}- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{
NSLog(@"Closed Reason:%@",reason);
self.title = @"Connection Closed! (see logs)";
self.webSocket = nil;
}- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload{
NSString *reply = [[NSString alloc] initWithData:pongPayload encoding:NSUTF8StringEncoding];
NSLog(@"%@",reply);
}#pragma mark - SendButton Response
- (IBAction)sendAction:(id)sender {
[self.view endEditing:YES];
if (self.webSocket) {
[self.webSocket send:@"test success"];
}
}
这样大概的聊天技术就完成了,当然这只是一个很简单的测试,具体开发要大家自己发挥
我在AppStroe上传了个APP叫《今日便签》,完美高仿鼎鼎大名的Clear,不仅免费还添加了许多新的功能,使用更爽更简洁,欢迎各位下载使用 : )