iOS-Socket/Tcp编程

很多同学一听到Socket TCP UDP 这几个字眼感觉特别害怕, 很怕在工作当中使用,因为他们有些底层了。下面是我在工作中使用Socket类库GCDAsyncSocket进行的一次应用。socket只适用于用户量偏小的app使用。如果数据量过大,请学习XMPP即时通讯协议。

集成步骤

  1. GCDAsyncSocket框架下载地址

  2. 向工程导入下面两个文件。

    • GCDAsyncSocket.h
    • GCDAsyncSocket.m
  3. 创建一个单例类Client 继承于NSObject

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #import <Foundation/Foundation.h>
    // 重定义block类型
    typedef void(^BLOCK)(id result);
    @interface RCClient : NSObject
    // 实现单例方法
    + (Client *)shareInstance;
    // 发送信息
    - (void)sendMessage:(NSString *)str complete:(BLOCK)block;
    @end
  4. Client.m 文件内容如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65

    #import "Client.h"
    #import "GCDAsyncSocket.h"
    // TCP连接
    @interface Client ()
    @property (nonatomic,strong)GCDAsyncSocket *socket;
    @property (nonatomic,copy)BLOCK block;
    @property (nonatomic,assign)NSInteger counter;
    #define IP @"192.168.1.100"
    #define PORT 5555
    @end

    @implementation Client
    #pragma mark - 初始化方法
    - (instancetype)init
    {
    self = [superinit];
    if (self) {
    [selfcreateConnection];
    }
    return self;
    }
    #pragma mark - 创建单例
    + (Client *)shareInstance {
    staticClient *client =nil;
    staticdispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    client = [[Clientalloc]init];
    });
    return client;
    }
    #pragma mark - 建立连接
    - (void)createConnection {
    self.socket = [[GCDAsyncSocketalloc]initWithDelegate:selfdelegateQueue:dispatch_get_main_queue()];
    // 连接
    NSError *error =nil;
    [self.socketconnectToHost:IPonPort:PORTerror:&error];
    if (error) {
    NSLog(@"连接错误%@", error);
    return;
    }
    [self.socketreadDataWithTimeout:-1tag:0];
    }
    #pragma mark - 发送数据
    - (void)sendMessage:(NSString *)str tag:(NSInteger)tag complete:(BLOCK)block {
    self.block = block;
    [self.socketwriteData:[strdataUsingEncoding:NSUTF8StringEncoding]withTimeout:-1tag:0];
    [self.socket readDataWithTimeout:-1 tag:0];
    }

    #pragma mark - 服务器返回数据
    - (void)socket:(GCDAsyncSocket*)sock didReadData:(NSData *)data withTag:(long)tag {
    NSString *str = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
    NSLog(@"str = %@", result);
    if(self.block) {
    self.block(result);
    }
    [self.socketreadDataWithTimeout:-1 tag:0];
    }
    #pragma mark - 服务器返回数据[
    - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
    NSLog(@"已经断开连接!");
    [self.socketreadDataWithTimeout:-1 tag:0];
    }
    @end