This article, we introduce the use of Cocoaasyncsocket framework, mainly introduce the implementation of client/server-side code, I believe that there are many such articles on the Internet, here to do their own summary. Here are the ways to use GCD
I. Client
1.
Readers can download the framework source code on GitHub Https://github.com/robbiehanson/CocoaAsyncSocket
After downloading, can see in examples below can see many examples, if the reader self-study ability high, can skip the following article.
2. Start using
1) in the \SOURCE\GCD directory, we can see Gcdasyncsocket h and M files, we copy these two files into the project.
2) We import the header file into the code #import "GCDAsyncSocket.h" and the Protocol gcdasyncsocketdelegate.
3. Code
1) Define global variables Gcdasyncsocket *_socket;
2) Start connecting to the server
- (void) Connect2server () {//1. Host and port numberNSString *host =@"127.0.0.1"; intPort =12345; //There are two ways to initialize a socket. Run the socket in the main/child thread, respectively. Varies by project_socket = [[Gcdasyncsocket alloc] initwithdelegate:self delegatequeue:dispatch_get_main_queue ()];//This is run in the main thread//_socket = [[Gcdasyncsocket alloc] initwithdelegate:self delegatequeue:dispatch_get_global_queue (DISPATCH_QUEUE_ Priority_default, 0)]; This is run in a child thread//Start ConnectionNserror *error =Nil; [_socket connecttohost:host onPort port error:&ERROR]; if(Error) {NSLog ("error:%@", error); } }
3) Login
-(void) login () { // login string "iam:i am login! " ; *logindata = [Loginstr datausingencoding:nsutf8stringencoding]; // Send login instructions. 1 means no time-out. TAG200 represents the logo of this directive, which is of great use [_socket writedata:logindata withtimeout:-1 tag: $];}
4) Start chatting
// Send chat Data -(void) sendmsg: (nsstring*) msg{ *sendmsg = [@ "msg:i Send Message To u! " ]; *senddata = [sendmsg datausingencoding:nsutf8stringencoding]; [_socket writedata; SendData withtimeout:-1 tag:201];}
5) Implement Protocol delegate
#pragmaMark-socket's agent#pragmaMark Connected successfully-(voidSocket: (Gcdasyncsocket *) sock didconnecttohost: (NSString *) host port: (uint16_t) port{//Connection SuccessfulNSLog (@"%s", __func__);}#pragmaMark Disconnects-(void) Socketdiddisconnect: (Gcdasyncsocket *) sock witherror: (Nserror *) err{if(Err) {NSLog (@"Connection Failed"); }Else{NSLog (@"Normal Disconnect"); }}#pragmaMark Data sent successfully-(voidSocket: (Gcdasyncsocket *) sock Didwritedatawithtag: (Long) tag{NSLog (@"%s", __func__); //Manual read after sending data[sock readdatawithtimeout:-1Tag:tag];}#pragmaMark reads the data-(voidSocket: (Gcdasyncsocket *) sock didreaddata: (NSData *) data withtag: (Long) tag{//the agent is called on the primary/sub-threadNSLog (@"%@", [Nsthread CurrentThread]); NSString*receiverstr =[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; if(Tag = = $) { //Login Instructions }Else if(Tag = =201){ //Chat Data} NSLog (@"%s%@", __FUNC__,RECEIVERSTR);}
Two. Server-side
The server side cannot run on Iphone/ipad, so we create a simple command line project.
1. Create a new class Mychatserver, and open the public method StartServer, the header file is as follows
#import <Foundation/Foundation.h>@interface mychatserver:nsobject/* * * */-(void) startserver; @end
2. In the main file, turn on the chat server and turn on the main run loop to have the server receive the client request
// Implementing Chat *chatserver = [[Mychatserver alloc] init];[ Chatserver StartServer]; // turn on the main run cycle [[Nsrunloop Currentrunloop] run];
3. In the mychatserver.m file, we begin to implement the Gcdasyncsocket method (the following code is in MYCHATSERVER.M)
1) First build a member variable array object, save all the socket (client) objects in the inside
@property (strong,nonatomic) Nsmutablearray *clientsocket;
Private variables ServerSocket and Golbal_queue
Gcdasyncsocket *_serversocket;dispatch_queue_t _golbalqueue;
2) In class initialization, we initialize the private variable and the member variable
-(instancetype) init{ if (self = [Super init]) { = [Nsmutablearray array]; // Create global queue 0); // create the socket for the server, note that this is the initialization and you have specified the delegate = [[Gcdasyncsocket alloc] initwithdelegate:self delegatequeue:_golbalqueue]; } return Self ;}
3) Turn on server chat StartServer
-(void) startchatserver{ // Open listening port
*err; [_serversocket Acceptonport: error:&err]; if (! err) { NSLog (@ " service turned on successfully "); } Else { NSLog (@ " Service failed to open ");} }
4) Implement Delegate
#pragma Mark has a client to establish a connection when calling-(void) Socket: (Gcdasyncsocket *) sock Didacceptnewsocket: ( Gcdasyncsocket *) newsocket{//sock is the socket on the server, the socket on the server is only responsible for the client connection and is not responsible for reading the data. Newsocket The socket for the client
NSLog (@"Socket %p on the server socket%p client", Sock,newsocket); //Save the client's socket, if not saved, the server will automatically disconnect the client (the client will report a disconnected log)NSLog (@"%s", __func__); [Self.clientsocket Addobject:newsocket]; //newsocket is the socket for the client. Herereading Data[Newsocket readdatawithtimeout:-1Tag -];}#pragma mark Server writes data to the client-(voidSocket: (Gcdasyncsocket *) sock Didwritedatawithtag: (Long) tag{NSLog (@"%s", __func__); [Sock readdatawithtimeout:-1Tag -];}#pragmaMark receives the data that the client passes over-(voidSocket: (Gcdasyncsocket *) sock didreaddata: (NSData *) data withtag: (Long) tag{ //sock for the client socket NSLog (@"the client socket%p", sock); //receiving DataNSString *receiverstr =[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"length:%ld", receiverstr.length); //The return and newline characters are removed, and the received string sometimes includes these 2, resulting in unequal judgment when the Quit command is judgedRECEIVERSTR = [Receiverstr stringbyreplacingoccurrencesofstring:@"\ r"Withstring:@""]; Receiverstr= [Receiverstr stringbyreplacingoccurrencesofstring:@"\ n"Withstring:@""]; //The command to determine whether to log in or send chat data. These directives are custom-defined//Login Instructions if([Receiverstr Hasprefix:@"iam:"]){
//Get user nameNSString *user = [Receiverstr componentsseparatedbystring:@":"][1]; //data that responds to the clientNSString *respstr = [user stringbyappendingstring:@"Has joined"];[Sock writedata:[respstr Datausingencoding:nsutf8stringencoding] withtimeout:-1Tag0]; } //Chat Instructions if([Receiverstr Hasprefix:@"msg:"]) { //Intercept Chat MessagesNSString *msg = [Receiverstr componentsseparatedbystring:@":"][1]; [Sock writedata:[msg datausingencoding:nsutf8stringencoding] Withtimeout:-1Tag0]; } //quit Command if([Receiverstr isequaltostring:@"quit"]) { //Disconnect Connection[sock disconnect]; //Remove Socket[Self.clientsocket Removeobject:sock]; } NSLog (@"%s", __func__);}
Before you view this article, you can look at
IOS Socket 03-Establish connection and login
IOS Socket 04-Using framework Cocoaasyncsocket to implement client/server side