iOS GCDAsyncSocket

开源地址:https://github.com/robbiehanson/CocoaAsyncSocket/wiki/Intro_GCDAsyncSocket

怎么样使用:看网站下面的具体使用说明。

封装后的代码

#import <UIKit/UIKit.h>
#import "GCDAsyncSocket.h"
#import "AmfMessage.h"

static const int HEADTAG = 0;
static const int BODYTAG = 1;

@class AmfHandler;

@interface ClientSocket : GCDAsyncSocket <UIApplicationDelegate>

@property (nonatomic, assign) int header;
@property (nonatomic, retain) AmfHandler *amfHandler;

- (BOOL)bind:(NSString *)host onPort:(int)port;
- (void)writer:(AmfMessage*)msg;
- (void)shutdown;

@end
//
//  ClientSocket.m
//  GameClientEngine
//
//  Created by chao zhang on 12-2-22.
//  Copyright (c) 2012骞?hangzhou. All rights reserved.
//

#import "ClientSocket.h"
#import "AmfMessageEncoder.h"
#import "AmfMessageDecoder.h"
#import "AmfHandler.h"

@implementation ClientSocket

@synthesize header;
@synthesize amfHandler;

- (id)init
{
    self = [super initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    header = 4;
    amfHandler = [[AmfHandler alloc]init];
    
    return self;
}

-(void)writer:(AmfMessage *)msg
{
    AmfMessageEncoder* encoder = [[AmfMessageEncoder alloc]init];
    NSData * encodeData = [encoder encode:msg];
    [self writeData:encodeData withTimeout:-1 tag:2];
}

- (void)socket:(ClientSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    if (tag == 0)
    {
        int8_t b[header];
        [data getBytes:b length:header];
        
        NSMutableData* tempData = [[NSMutableData alloc] init];
        for(int bb = header - 1 ;bb > -1;bb--)
        {
            int8_t temp = b[bb];
            [tempData appendBytes:&temp length:sizeof(temp)];
        }
        
        int headlength;
        [tempData getBytes:&headlength range:NSMakeRange(0, sizeof(headlength))];
        [sock readDataToLength:headlength withTimeout:-1 tag:BODYTAG];
        
    }
    else if (tag == 1)
    {
        AmfMessageDecoder *decoder = [[AmfMessageDecoder alloc]init];
        AmfMessage *msg = [decoder decode:data];
        [amfHandler messageReceived:msg socket:self];
        [sock readDataToLength:header withTimeout:-1 tag:HEADTAG];
    }
}

- (BOOL)bind:(NSString *)host onPort:(int)port
{
    NSError *error = nil;
    if (![self connectToHost:host onPort:port error:&error])
    {
        NSLog(@"Error connecting: %@", error);
        return NO;
    }
    else
    {
        [self readDataToLength: header withTimeout:-1 tag:HEADTAG];
        return YES;
    }
}

- (void)shutdown
{
    [self disconnect];
}

@end






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值