GCDAsyncSocket-客户端

//
//  ViewController.m
//  TestCocoaAsyncSocket
//
//  Created by dj on 2017/6/15.
//  Copyright © 2017年 djlovettt. All rights reserved.
//

#import "ViewController.h"
#import "GCDAsyncSocket.h"

@interface ViewController ()

@property (nonatomic, strong) GCDAsyncSocket *clientSocket;
@property (nonatomic, strong) NSTimer *connectTimer;
@property (nonatomic, assign) BOOL connected;

@property (nonatomic, assign) NSInteger port;
@property (nonatomic, copy)   NSString *hostAddress;

@property (nonatomic, copy) NSString *sendMessage;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    _port = 8080;
    _hostAddress = @"192.***.1.***";
    _sendMessage = @"这是一条测试数据";
}

/**
 开始进行 socket 连接
 */
- (void)startConnect {
    if (!self.connected) {
        self.clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        NSLog(@"开始进行 socket 连接");
        
        NSError *error = nil;
        self.connected = [self.clientSocket connectToHost:_hostAddress onPort:_port viaInterface:nil withTimeout:-1 error:&error];
        if (self.connected) {
            NSLog(@"正在尝试连接");
        } else {
            NSLog(@"客户端未创建连接");
        }
    } else {
        NSLog(@"socket 连接成功");
    }
}

/**
 向服务器端发送消息
 */
- (void)sendMessageAction {
    NSData *data = [_sendMessage dataUsingEncoding:NSUTF8StringEncoding];
    //withTimeout:-1 表示一直等待
    //tag 消息标记
    [self.clientSocket writeData:data withTimeout:-1 tag:0];
}

/**
 连接服务器对应的端口号

 @param sock 客户端的 socket
 @param host 主机 IP
 @param port 端口号
 */
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    //连接成功后开启定时器
    [self addTimer];
    
    [self.clientSocket readDataWithTimeout:-1 tag:0];
    self.connected = YES;
}

- (void)addTimer {
    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];
    //将定时器添加到 runloop 里
    [[NSRunLoop currentRunLoop] addTimer:self.connectTimer forMode:NSRunLoopCommonModes];
}

- (void)longConnectToSocket {
    //发送固定内容至服务器
    float version = [[UIDevice currentDevice] systemVersion].floatValue;
    NSString *versionStr = [NSString stringWithFormat:@"djlovett_%.2f",version];
    
    NSData *data = [versionStr dataUsingEncoding:NSUTF8StringEncoding];
    [self.clientSocket writeData:data withTimeout:-1 tag:0];
}

/**
 读取接收到的数据

 @param sock 客户端 socket
 @param data 接收到的数据
 @param tag  数据标记
 */
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"接收到的数据为 === %@",content);
    
    //读取到服务器数据数值后,可以再次读取
    [self.clientSocket readDataWithTimeout:-1 tag:0];
}

/**
 客户端断开连接

 @param sock 客户端socket
 @param err  错误信息
 */
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
    NSLog(@"socket 断开连接");
    NSLog(@"错误信息描述: %@",err.localizedDescription);
    self.clientSocket.delegate = nil;
    self.clientSocket = nil;
    self.connected = NO;
    [self.connectTimer invalidate];
}

@end

你可能感兴趣的:(GCDAsyncSocket-客户端)