iOS WebsocketStompKit 用法

为了实现iOS客户端与后台即时通讯
参考链接
首先导入SDK到项目中

用pod的话
pod 'WebsocketStompKit', :git => 'https://github.com/rguldener/WebsocketStompKit.git'
1.建立连接
2.断开连接
3.监听连接状态
#import "ViewController.h"
#import <WebsocketStompKit/WebsocketStompKit.h>
@interface ViewController ()<STOMPClientDelegate>
@property (nonatomic, strong) STOMPClient *client;
@end

@implementation ViewController
//1.建立连接
- (IBAction)connectAction:(id)sender {
    NSURL *websocketUrl = [NSURL URLWithString:@"ws://message.aoliliya.com/messages/websocket"];
    STOMPClient *client = [[STOMPClient alloc] initWithURL:websocketUrl webSocketHeaders:@{@"Cookie": @"AOLILIYAID=f42fc449-500a-4c6c-b038-4106c7fe101e"} useHeartbeat:YES];
    //建立连接
    self.client = client;
    [client connectWithHeaders:@{@"Cookie": @"AOLILIYAID=f42fc449-500a-4c6c-b038-4106c7fe101e"} completionHandler:^(STOMPFrame *connectedFrame, NSError *error) {
        if (error) {
            NSLog(@"%@", error);
            return;
        }
        //注册协议
        [client subscribeTo:@"/user/topic/messages" messageHandler:^(STOMPMessage *message) {
            NSLog(@"body = %@",message.body);
        }];
        // send a message
        [client sendTo:@"/app/content" body:@"{\"type\":1,\"content\":123,\"objId\":90028,\"createDate\":1523502141289}"];

    }];
     client.delegate = self; //添加代理监听连接状态

}
//2.断开连接
- (IBAction)disconnectAction:(id)sender {
     [self.client disconnect];
}
//3.与后台断开连接的回调方法 STOMPClientDelegate
- (void)websocketDidDisconnect:(NSError *)error {
    //在这里处理断开连接之后的逻辑,比如是否需要重新连接
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

附上自己写的Demo地址

还有不明白的地方欢迎留言!

//这是sdk里边的方法,我给修改了一下
+ (STOMPFrame *) STOMPFrameFromData:(NSData *)data {
    NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])];
    NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
    LogDebug(@"<<< %@", msg);
    NSMutableArray *contents = (NSMutableArray *)[[msg componentsSeparatedByString:kLineFeed] mutableCopy];
    while ([contents count] > 0 && [contents[0] isEqual:@""]) {
        [contents removeObjectAtIndex:0];
    }
    if (!contents.count) {
        return nil;
    }
    NSString *command = [[contents objectAtIndex:0] copy];
    NSMutableDictionary *headers = [[NSMutableDictionary alloc] init];
    NSMutableString *body = [[NSMutableString alloc] init];
    BOOL hasHeaders = NO;
    [contents removeObjectAtIndex:0];
    
    for(NSString *line in contents) {
        if(hasHeaders) {
            if (headers[@"content-length"]) {
                //新加的判断方法
                int contentLength =  [headers[@"content-length"] integerValue];
                body = [line substringWithRange:NSMakeRange(0, line.length)];
            }else {
                //初始版本
                for (int i=0; i < [line length]; i++) {
                    unichar c = [line characterAtIndex:i];
                    if (c != '\x00') {
                        [body appendString:[NSString stringWithFormat:@"%c", c]];
                        
                    }
                }
            }

            
        } else {
            if ([line isEqual:@""]) {
                hasHeaders = YES;
            } else {
                NSMutableArray *parts = [NSMutableArray arrayWithArray:[line componentsSeparatedByString:kHeaderSeparator]];
                // key ist the first part
                NSString *key = parts[0];
                [parts removeObjectAtIndex:0];
                headers[key] = [parts componentsJoinedByString:kHeaderSeparator];
            }
        }
    }
    return [[STOMPFrame alloc] initWithCommand:command headers:headers body:body];
}

推荐阅读更多精彩内容