webSocket开源框架:SocketRocket
2016-02-18 本文已影响10659人
月咏蝴蝶
- 下载解压文件打开SocketRocket文件夹
- 把这个文件夹的文件拉到自己项目里面去
- 添加配置文件
- 实现代码
使用以下测试地址亲测可用
测试地址:ws://echo.websocket.org
#import "SRWebSocket.h"
初始化
- (void)Reconnect{
self.webSocket.delegate = nil;
[self.webSocket close];
self.webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://echo.websocket.org"]]];
self.webSocket.delegate = self;
self.title = @"Opening Connection...";
[self.webSocket open];
}
- (void)viewWillAppear:(BOOL)animated{
[self Reconnect];
}
- (void)viewDidDisappear:(BOOL)animated{
// Close WebSocket
self.webSocket.delegate = nil;
[self.webSocket close];
self.webSocket = nil;
}
代理方法实现
#pragma mark - SRWebSocketDelegate
- (void)webSocketDidOpen:(SRWebSocket *)webSocket{
NSLog(@"Websocket Connected");
self.title = @"Connected!";
}
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
NSLog(@":( Websocket Failed With Error %@", error);
self.title = @"Connection Failed! (see logs)";
self.webSocket = nil;
}
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
NSString *str1 = self.replyContent.text;
NSString *str2 = [str1 stringByAppendingFormat:@"%@\n",message];
self.replyContent.text = str2;
}
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{
NSLog(@"Closed Reason:%@",reason);
self.title = @"Connection Closed! (see logs)";
self.webSocket = nil;
}
- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload{
NSString *reply = [[NSString alloc] initWithData:pongPayload encoding:NSUTF8StringEncoding];
NSLog(@"%@",reply);
}
#pragma mark - SendButton Response
- (IBAction)sendAction:(id)sender {
[self.view endEditing:YES];
// WebSocket
if (self.webSocket) {
[self.webSocket send:@"test success"];
}
}