开源地址:https://github.com/robbiehanson/CocoaAsyncSocket/wiki/Intro_GCDAsyncSocket
怎么样使用:看网站下面的具体使用说明。
封装后的代码;
//
// ClientSocket.h
// GameClientEngine
//
// Created by chao zhang on 12-2-22.
// Copyright (c) 2012骞?hangzhou. All rights reserved.
//
#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