下面是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
最後調試,成功,附上壹張效果!