Open Source Address: https://github.com/robbiehanson/CocoaAsyncSocket/wiki/Intro_GCDAsyncSocket
How to Use: see the specific instructions under the website.
Encapsulated code;
//
// Clientsocket. h
// Gameclientengine
//
// Created by Chao Zhang on 12-2-22.
// Copyright (c) 2012 seconds? 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 seconds? 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