美文网首页
OC websocket

OC websocket

作者: Albert新荣 | 来源:发表于2019-03-26 23:23 被阅读0次
    #import "SRWebSocket.h"
    
    #import <UIKit/UIKit.h>
    #import "SocketRocket.h"
    
    @interface ViewController : UIViewController<SRWebSocketDelegate>
    
    @property (nonatomic,strong)SRWebSocket *webSocket;
    
    @end
    
    #import "ViewController.h"
    
    @interface ViewController ()
    @property (weak, nonatomic) IBOutlet UILabel *showTxt;
    
    @end
    
    @implementation ViewController
    
    - (void)viewWillAppear:(BOOL)animated{
        [self Reconnect];
    }
    
    - (void)viewDidDisappear:(BOOL)animated{
        // Close WebSocket
        self.webSocket.delegate = nil;
        [self.webSocket close];
        self.webSocket = nil;
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
    
    }
    //初始化
    - (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)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 {
        NSLog(@"Received \"%@\"", message);
        self.showTxt.text = message;
    }
    // 长连接关闭
    - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
        NSLog(@"WebSocket closed");
        self.title = @"Connection Closed! (see logs)";
        self.webSocket = nil;
    }
    //该函数是接收服务器发送的pong消息
    - (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload {
        NSString *reply = [[NSString alloc] initWithData:pongPayload encoding:NSUTF8StringEncoding];
        NSLog(@"%@",reply);
    }
    
    - (IBAction)sendAction:(id)sender {
        
        [self.view endEditing:YES];
        // WebSocket
        if (self.webSocket) {
            [self.webSocket send:@"test success"];
        }
    }
    ~~
    
    本文来自于[](ttps://www.cnblogs.com/ningmengcao-ios/p/5941993.html)

    相关文章

      网友评论

          本文标题:OC websocket

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