网络层(socket、Net)OC开发iOS成仙之路

webSocket开源框架:SocketRocket

2016-02-18  本文已影响10659人  月咏蝴蝶

git下载地址:square/SocketRocket

  1. 下载解压文件打开SocketRocket文件夹
E18C88E4-8586-429B-8B69-FC7FE9277064.png
  1. 把这个文件夹的文件拉到自己项目里面去
  2. 添加配置文件
92E76BD6-DB41-4FFD-86D8-253CA93478FB.png

添加.pch文件方法步骤

  1. 实现代码

使用以下测试地址亲测可用
测试地址: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"];
    }
}
上一篇下一篇

猜你喜欢

热点阅读