【转】iOS websocket 及时通讯实现

原文网址:http://blog.csdn.net/manyxh/article/details/48196209

    2015-09-03 by 木易哥哥 

   开发一个类似QQ、微信的即时IM聊天功能,做到实时监控消息,需要用的技术是websocket,WebSocket protocol 是HTML5一种新的协议。它实现了浏览器与服务器全双工通信(full-duplex)。在 WebSocket API,浏览器和服务器只需要要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

      下面是iOS端我实现websocket通讯,列出步骤思路,以作学习。

1.加入frameworks的 libicucore.dylib

2.导入对象SRWebSocket

3.在聊天的viewController.h引用 #import "SRWebSocket.h"头文件   SRWebSocketDelegate代理,声明SRWebSocket *_webSocket;

4.在聊天的viewController.m使用

- (void)connectSocket

{

    if (_webSocket ==nil) {

        _webSocket = [[SRWebSocketalloc]initWithURLRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:Web_Socket]]];

        _webSocket.delegate =self;

        [_webSocket open];

    }

}

#pragma mark - SRWebSocketDelegate 写上具体聊天逻辑

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

{

   // NSLog(@"Websocket Connected");

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

    [dictionary setValue:@"subscribe" forKey:@"cmd"];

    [dictionary setValue:@(VER)  forKey:@"ver"];

    [dictionary setValue:[settingInfo getSessionId] forKey:@"sid"];

    [dictionary setValue:@"1" forKey:@"channel"];

    [dictionary setValue:[[settingInfo getUserAccountInfo]objectForKey:@"user_id"] forKey:@"client_id"];

    //NSLog(@"dictionary:%@",[dictionary JSONString]);

    

    [_webSocket send:[dictionary JSONString]];

}

......

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

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message//监控消息

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

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload

最后调试,成功,附上一张效果!




原文地址:https://www.cnblogs.com/wi100sh/p/5995516.html