即时通讯之webSocket使用(三)

在H5兴起之后,单纯的socket开发已经很难满足开发的需求,因此一种新的基于H5即时通讯方式应运而生了,这就是本文要讲的websocket了,对于websoket理论方面的知识,大家可以看下这篇文章ios webSocket详解,下面就讲讲基于socketRocket这个第三方框架的开发,可以在github下载。

一、初始化

#import "ViewController.h"
#import "SRWebSocket.h"
@interface ViewController ()
@property(nonatomic,strong) SRWebSocket *webSocket;
@end
@implementation ViewController
 
- (void)viewDidLoad {
  [super viewDidLoad];
}

- (void)Reconnect{
NSLog(@"heheh---open");
self.webSocket.delegate = nil;
[self.webSocket close];
self.webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"[ws://192.168.1.110:410](ws://192.168.1.110:410/)"]]];
self.webSocket.delegate = self;
self.title = @"webSocket开始连接了";
[self.webSocket open];
}

- (void)viewDidDisappear:(BOOL)animated{
  // Close WebSocket
  self.webSocket.delegate = nil;
  [self.webSocket close];
  self.webSocket = nil;
 }

二.SRWebSocketDelegate

//连接成功
//代理方法实现

#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{
//  NSString *str1 = self.replyContent.text;
//  NSString *str2 = [str1 stringByAppendingFormat:@"%@\n",message];
//  self.replyContent.text = str2;
 
  NSLog(@"%@--askl",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;
 }

//该函数是接收服务器发送的pong消息,其中最后一个是接受pong消息的,
在这里就要提一下心跳包,一般情况下建立长连接都会建立一个心跳包,
用于每隔一段时间通知一次服务端,客户端还是在线,这个心跳包其实就是一个ping消息,
我的理解就是建立一个定时器,每隔十秒或者十五秒向服务端发送一个ping消息,这个消息可是是空的

- (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];
  // WebSocket
  if (self.webSocket) {
 
    [self.webSocket send:@"hello world !"];
 
  }
}

写在最后
我平时对常用socket的见解到此都分享出来了,还有socket.io以前也了解过,和Nodejs结合比较好,去年还只有swift版本,但是是基于轮询的方式,因此运行会比较的慢,大家有兴趣可以去研究研究

你可能感兴趣的:(即时通讯之webSocket使用(三))