美文网首页ios iOS Developer
iOS webSocket之单利简单实现即时通讯

iOS webSocket之单利简单实现即时通讯

作者: 花花也是我 | 来源:发表于2017-01-05 15:50 被阅读577次

    1.pod 下载RACSRWebSocket

    2.添加包

    Security.framework

    Foundation.framework

    CFNetwork.framework

    libicucore.A.tbd

    libicucore.tbd

    3.创建单利

    导入#import <SocketRocket/SRWebSocket.h>

    .h中的方法

    .m中的具体实现

    首先是 socket必须实现的代理方法 

    -(void)webSocketDidOpen:(SRWebSocket *)webSocket{

    NSLog(@"WebSocket DidOpen");

    [webSocket send:jsonString];//打开socket后根据后端要求传入字典字符串

    }

    -(void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{

    //socket接收到信息后通过代理传给外部使用

    [self.delegate getMessageFromSocket:dic];

    }

    -(void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{

    NSLog(@"WebSocket closed");

    }

    -(void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{

    NSLog(@":( Websocket Failed With Error %@", error);

    }

    下面是几个供外部调用的方法

    //因为URL不可能是死的需要从接口中获取,所以这个方法用于在接口中拿到URL

    - (void)WithIP:(NSString *)URLIP{

    _webSocket.delegate = nil;

    [_webSocket close];

    NSString *urlStr = [NSString stringWithFormat:@"%@", URLIP];

    NSURL *url = [NSURL URLWithString:urlStr];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //如需更改链接的头部则需此步

    [request setValue:@"http://xxxxxx" forHTTPHeaderField:@"xxx"];

    _webSocket = [[SRWebSocket alloc] initWithURLRequest:request];

    _webSocket.delegate = self;

    }

    //拿到URL后可以打开webSocket

    - (void)openSocket {

    [_webSocket open];

    }

    //退出页面时记得关闭webSocket

    - (void)closeSocket {

    self.webSocket.delegate = nil;

    [self.webSocket close];

    self.webSocket = nil;

    }


    //外部聊天发送消息给webSocket

    - (void)sendTalkMessage:(NSString *)message{

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];

    dic = [@{ @"content":message} mutableCopy];

    [self sendMessage:dic];

    }

    4.在ViewController中调用

    导入#import "webSocketManager.h"

    创建单利

    @property (nonatomic, strong) webSocketManager *webSocket;

    下面是几个主要的方法使用

    感兴趣的可以具体下载个demo看看,地址:

    https://github.com/Flower0120/webSocketDemo.git

    相关文章

      网友评论

        本文标题:iOS webSocket之单利简单实现即时通讯

        本文链接:https://www.haomeiwen.com/subject/vvlzvttx.html