1. 程式人生 > >iOS通過SocketRocket實現websocket的即時聊天

iOS通過SocketRocket實現websocket的即時聊天

最近專案中要做即時通訊功能, 但沒打算使用環信,融雲等三方平臺, 我查了一下資料,ios端實現起來還是比較簡單的 ,我也寫了一個小demo,和大家分享一下

首先到getHub上下載一個 FaceBook的 SocketRocket, 然後倒入工程; 我是直接使用 pod匯入SocketRocket

首先pod匯入SocketRocket

platform :ios, '8.0'
pod 'SocketRocket', '~> 0.5.0'

在控制器中匯入標頭檔案

#import <SocketRocket/SRWebSocket.h>

然後就可以使用webSocket了, 其實裡面的東西也不是很多, 主要是: 1.開啟連線 2.關閉連線 3.傳送訊息 4.接收訊息;

簡單粗暴的直接上程式碼吧

#import "ViewController.h"

#import "Masonry.h"                  // 實現自動佈局的 
#import <SocketRocket/SRWebSocket.h>

#define HHMainScreenWidth [UIScreen mainScreen].bounds.size.width
#define HHMainScreenHeight [UIScreen mainScreen].bounds.size.height

@interface ViewController ()<SRWebSocketDelegate, UITextFieldDelegate, UITextViewDelegate>

@property(nonatomic, strong)UITextView *shouField;
@property(nonatomic, strong)UITextField *FaField; @property(nonatomic, strong)SRWebSocket *webSocket; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self createView]; } // 啟動 webSocket - (void)setSocket { _webSocket.delegate = nil; [_webSocket close];
// _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://114.55.57.51:8282"]]]; _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://10.220.117.205:8081/websocket"]]]; _webSocket.delegate = self; NSLog(@"Opening Connection..."); [_webSocket open]; } // 協議方法 連結成功 給伺服器傳送id - (void)webSocketDidOpen:(SRWebSocket *)webSocket { NSLog(@"Websocket Connected"); // 如果需要傳送資料到伺服器使用下面程式碼 NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:@{@"id":@"chat",@"clientid":@"hxz",@"to":@""} options:NSJSONWritingPrettyPrinted error:&error]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; [webSocket send:jsonString]; } // 協議方法 接收訊息 - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message { NSLog(@"接收的訊息:%@", message); self.shouField.text = message; } // 協議方法 Websocket 開啟失敗 - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error { NSLog(@":( Websocket 開啟失敗 %@", error); webSocket = nil; // 斷開連線後每過1s重新建立一次連線 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self setSocket]; }); } // 連線關閉 - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean { NSLog(@"WebSocket closed, reason:%@", reason); webSocket = nil; } - (void)sendButAction { NSLog(@"傳送"); if (self.FaField.text.length > 0) { [_webSocket send:self.FaField.text]; } else { NSLog(@"輸入為空"); } } - (void)openButAction { NSLog(@"開啟"); [self setSocket]; // 啟動 webSocket } - (void)offButAction { NSLog(@"關閉"); _webSocket.delegate = nil; [_webSocket close]; } -(void)createView { UILabel *jieshouLabel = [UILabel new]; jieshouLabel.text = @"接收:"; jieshouLabel.backgroundColor = [UIColor clearColor]; [self.view addSubview:jieshouLabel]; [jieshouLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self.view).offset(10); make.height.mas_equalTo(40); make.left.equalTo(self.view).offset(10); }]; UITextView *shouField = [UITextView new]; shouField.delegate = self; shouField.textColor = [UIColor whiteColor]; shouField.backgroundColor = [UIColor grayColor]; shouField.returnKeyType = UIReturnKeySearch; shouField.font = [UIFont systemFontOfSize:13]; shouField.layer.masksToBounds = YES; shouField.layer.cornerRadius = 5; [self.view addSubview:shouField]; [shouField mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(jieshouLabel.mas_bottom).offset(5); make.height.mas_equalTo(140); make.left.equalTo(self.view).offset(10); make.right.equalTo(self.view).offset(-10); }]; self.shouField = shouField; UILabel *faSongLabel = [UILabel new]; faSongLabel.text = @"傳送:"; faSongLabel.backgroundColor = [UIColor clearColor]; [self.view addSubview:faSongLabel]; [faSongLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(shouField.mas_bottom).offset(10); make.height.mas_equalTo(40); make.left.equalTo(self.view).offset(10); }]; // 發 UITextField *FaField = [UITextField new]; FaField.delegate = self; FaField.textColor = [UIColor whiteColor]; FaField.backgroundColor = [UIColor grayColor]; FaField.returnKeyType = UIReturnKeySearch; FaField.font = [UIFont systemFontOfSize:13]; FaField.layer.masksToBounds = YES; FaField.layer.cornerRadius = 5; [self.view addSubview:FaField]; [FaField mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(faSongLabel.mas_bottom).offset(5); make.height.mas_equalTo(40); make.left.equalTo(self.view).offset(10); make.right.equalTo(self.view).offset(-10); }]; self.FaField = FaField; UIButton *but = [UIButton buttonWithType: UIButtonTypeCustom]; but.backgroundColor = [UIColor greenColor]; [but setTitle:@"傳送" forState:UIControlStateNormal]; but.layer.masksToBounds = YES; but.layer.cornerRadius = 5; [but addTarget:self action:@selector(sendButAction) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:but]; [but mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.equalTo(self.view); make.height.mas_equalTo(40); make.width.mas_equalTo(HHMainScreenWidth - 60); make.top.equalTo(FaField.mas_bottom).offset(20); }]; // 開啟 UIButton *openBut = [UIButton buttonWithType: UIButtonTypeCustom]; openBut.backgroundColor = [UIColor orangeColor]; [openBut setTitle:@"開啟" forState:UIControlStateNormal]; openBut.layer.masksToBounds = YES; openBut.layer.cornerRadius = 5; [openBut addTarget:self action:@selector(openButAction) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:openBut]; [openBut mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.view).offset(20); make.height.mas_equalTo(40); make.width.mas_equalTo(100); make.top.equalTo(but.mas_bottom).offset(20); }]; // 關閉 UIButton *offBut = [UIButton buttonWithType: UIButtonTypeCustom]; offBut.backgroundColor = [UIColor orangeColor]; [offBut setTitle:@"關閉" forState:UIControlStateNormal]; offBut.layer.masksToBounds = YES; offBut.layer.cornerRadius = 5; [offBut addTarget:self action:@selector(offButAction) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:offBut]; [offBut mas_makeConstraints:^(MASConstraintMaker *make) { make.right.equalTo(self.view).offset(-20); make.height.mas_equalTo(40); make.width.mas_equalTo(100); make.top.equalTo(but.mas_bottom).offset(20); }]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end

要實現給好友,群主發訊息等功能,需要後臺做寫工作, 前端再和後臺約定一下使用者ID什麼的, 前端這邊工作量不大,實現起來還是比較簡單的;