A lot of students hear the socket TCP UDP these words feel particularly afraid, very afraid to use in the work, because they are too low. I'm working with the Socket class library Gcdasyncsocket.
The article only applies to small data transmission, if the comparison, such as audio files, please splicing data itself.
First, import gcdasyncsocket.h/gcdasyncsocket.m into the project
: Link: Http://pan.baidu.com/s/1c1bHytM Password: p22g
Then create a singleton class client that inherits from the NSObject
Client.h file contents are as follows
#import <Foundation/Foundation.h>
typedef void(^block) (IDresult);
@interface rcclient: nsobject
+ (Client *) shareinstance;
-(void) SendMessage: (nsstring *) str complete: (block) block;
@end
The contents of the CLIENT.M file are as follows:
#import "Client.h"
#import "GCDAsyncSocket.h"
TCP Connections
@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
@implementationClient
-(instancetype) init
{
Self = [superinit];
If (self) {
[selfcreateconnection];
}
Return self;
}
+ (Client *) shareinstance {
StaticClient *client =nil;
Staticdispatch_once_t oncetoken;
Dispatch_once(&oncetoken, ^{
client = [[Clientalloc]init];
});
return client;
}
#pragma mark- Establish a connection
-(void) createconnection {
Self. Socket = [[gcdasyncsocketalloc]initwithdelegate:selfdelegatequeue: Dispatch_get_main_queue()];
Connection
Nserror *error =nil;
[self. Socketconnecttohost:IPonPort:PORTerror:&error];
If(error) {
NSLog(@ " connection error %@", error);
Return
}
[self. Socketreaddatawithtimeout:-1tag:0];
}
Send Data
-(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];
}
TCP Connections
-(void) Socket: (gcdasyncsocket *) sock didconnecttohost: (nsstring *) host port: (uint16_t ) port {
NSLog(@ " connected successfully ");
[self. Socketreaddatawithtimeout:-1tag:0];
}
-(void) disconnection {
[self. SocketDisconnect];
[self. Socketreaddatawithtimeout:-1tag:0];
}
Server returns data
-(void) Socket: (gcdasyncsocket*) sock didreaddata: (nsdata *) data withtag: (long ) Tag {
NSString *str = [[nsstringalloc]initwithdata:d ataencoding: Nsutf8stringencoding];
NSLog(@ "str =%@", result);
Self. Block(result);
[self. Socketreaddatawithtimeout:-1tag:0];
}
-(void) Socketdiddisconnect: (gcdasyncsocket *) sock witherror: (nserror *) Err {
NSLog(@ " already disconnected !") );
[self. Socketreaddatawithtimeout:-1tag:0];
}
@end
Transferred from: http://blog.5ibc.net/p/32842.html
IOS SOCKET/TCP Programming Gcdasyncsocket in combat (with callbacks)