iOS之WebSocket(即时通讯、实时接受广播消息)

在项目中使用到了广播消息,例如广播通知
首先导入

pod 'SocketRocket', '~> 0.5.0'

引入4个库
libicucore.dylib,CFNetwork.framework, Security.framework, Foundation.framework
这里写图片描述

#import "dynamicMessageTableViewCell.h"
#import "BBCyclingLabel.h"
#import <SocketRocket/SRWebSocket.h>

@interface dynamicMessageTableViewCell()<SRWebSocketDelegate>
{
    BBCyclingLabel * _bbCyclingLable;
    NSMutableArray * _titleArr;
//    UITextField * _text;
    int a;
    int _msgCount;
    SRWebSocket * _webSocket;

}

@end

@implementation dynamicMessageTableViewCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

        a = 0;
        _titleArr = [[NSMutableArray alloc] init];

        UIImageView *imagev = [[UIImageView alloc]initWithFrame:CGRectMake(12, 4, 14, 12)];
        [imagev setImage:GetImage(@"ico-notice.png")];
        [self addSubview:imagev];
        [self createUI];
    }
    return self;
}

-(void)createUI
{
//获取本地存储的数据
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray *myArray = [[NSArray alloc] initWithArray:[userDefaultes arrayForKey:@"messageArray"]];
    _titleArr = [myArray mutableCopy];

    _bbCyclingLable  = [[BBCyclingLabel alloc]initWithFrame:CGRectMake(40, 0, SCREEN_WIDTH-40, 20) andTransitionType:BBCyclingLabelTransitionEffectScrollUp];
    _bbCyclingLable.font = GetFont(BFONT_12);
    _bbCyclingLable.clipsToBounds = YES;
    [self addSubview:_bbCyclingLable];

    NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(change) userInfo:nil repeats:YES];
    [time fire];

    _webSocket.delegate = nil;
    [_webSocket close];
    _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://49.213.11.服务器端口"]]];

    _webSocket.delegate = self;
    [_webSocket open];
}

//数组中的内容仅供测试用,具体内容可以通过后台服务器获取或者写死(数据条数可以改变,我写的是3条)
-(void)change
{
    if (_titleArr.count >0) {
        if (0<=a && a<_titleArr.count) {
            _bbCyclingLable.text = [_titleArr objectAtIndex:a];
        }else{
            a=0;
            _bbCyclingLable.text = [_titleArr objectAtIndex:a];
        }
        a++;
    }
}

//这个的目的是往服务器上传数据,做即时通讯的时候发送的消息用这个方法

#pragma mark - SRWebSocketDelegate
- (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 didFailWithError:(NSError *)error;{

    NSLog(@":( Websocket Failed With Error %@", error);
    webSocket = nil;
}

//收到的消息
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;{

    NSLog(@"Received \"%@\"", message);
    NSString * mesStr = (NSString *)message;
    NSArray * arr = [mesStr componentsSeparatedByString:@","];

    for (NSString * str in arr) {
        [_titleArr addObject:str];
        //最多存5条记录
        if(_titleArr.count > 5)
        {
            [_titleArr removeObjectAtIndex:0];
        }
    }

    //将上述数据全部存储到NSUserDefaults中
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:_titleArr forKey:@"messageArray"];
}

//结束关闭
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;{

    NSLog(@"WebSocket closed");
    webSocket = nil;
}

有一个发送消息的demo(网上找的)
https://github.com/square/SocketRocket
https://github.com/facebook/SocketRocket
server的例子参考(网上找的)
http://haoningabc.iteye.com/blog/2124605

参考http://wenxin2009.iteye.com/blog/1707304

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值