iOS Development--gcdasyncsocket

Source: Internet
Author: User

The new company in the smart home, just tidy up its related technology! First, start with the problem of Gcdasyncsocket.

As the name Gcdasyncsocket the open source class library is an asynchronous interactive socket communication that is done with Apple's GCD multi-tasking mechanism. The use of the method is not complicated . each Gcdasyncsocket object (hereinafter referred to as the Gcdsocket object) can be understood as a socket socket, our operation is for the socket execution of the various commands, you can open a port to listen, you can also connect to other computer ports for data communication, etc. 。

Let's start by creating a socket. The source code is as follows:

Gcdasyncsocket socket = [[Gcdasyncsocket alloc] initwithdelegate:self delegatequeue:dispatch_get_main_queue ()];

The code is not complicated, we just need to give a delegate object, the self in the first argument, and a gcd queue that the delegate runs to create a gcdasyncsocket, which is the main message queue that we get with the static global function in the current code. It is also possible to use other methods to get other GCD queues, such as: Dispatch_get_global_queue ().

The socket object is created and we can understand that our socket is currently in the process for operation. But if you want to communicate with the server, then we also need to connect with the server. Maybe some people who used the HTTP protocol would ask, why don't we just specify the server and port number in the initialization function? In fact, these must all be needed, but you have to understand that your socket object function can not only be used to connect to the server, in other words, our socket object can listen to a port to wait for others to connect, So when using the TCP protocol via socket programming is a transition from the HTTP protocol over to the TCP protocol, we're going to use a protocol, not a class, So what I said above is that from the HTTP protocol over to TCP instead of saying that now we're going to be nsurlrequest and nsurlconnection over to Gcdasyncsocket.

Okay, let's see how to connect to the server next. The source code is as follows:

Nserror *error = nil;

if (![ Socket connecttohost:@ "192.168.16.254" onport:5001 Error:&error]) {

Uialertview *alert=[[uialertview alloc]initwithtitle:nil message:@ "Connection error, unable to configure! "Delegate:nil cancelbuttontitle:nil otherbuttontitles:@" OK ", nil];

[Alert show];

}else{

NSLog (@ "connected successfully");

}

We just first declare a pointer to the error message, and then use the object created earlier to call his connection method, which itself is to return a successful connection of the bool value, easy to use, the first parameter is not difficult to see is an IP, the second parameter is a port, the last is a parameter, If an error occurs during the connection, the method will point the pointer to a specific error message, and finally we will determine whether the pointer we created for the error message is still pointing to null, if it is not pointing to null then there is an error in the process of connecting to us, print the error message ~ but remember, The error message here is not that all errors will be reflected here when you create the connection.

Speaking of which, we should say something really useful, Gcdasyncsocket has a series of complete delegation mechanism, we do all the processing basically is the state of asynchronous processing, in other words, after the connection is successful, What to do if the connection is successful it should not be written here and should be written in the corresponding delegate, the same applies to sending, reading data and so on. That is, the error we read here is just the error that occurs when the code that is executing synchronously handles some connections, and more processing should be handled in the corresponding delegate. First, take a look at the following method:

-(void) Socket: (Gcdasyncsocket *) sock didconnecttohost: (NSString *) host port: (uint16_t) port

This method is the delegate method after the successful connection to the server. In this delegate method, we can take a socket object a server IP and a port number, you can handle everything should be done immediately after the connection is established, such as communication with the server to confirm the connection to avoid other people through the IP and port arbitrary and your server communication, Another example is to open the heartbeat packet sent, so that the server has been able to confirm your presence. No matter what you do, you and the server writer beforehand agreed, like data transmission format and so on.

Regardless of what you are doing here and what you have to deal with, be sure to remember that here you have to add a sentence at the end of the function:

[Socket readdatawithtimeout:-1 tag:0];

What is it? According to the first reaction you see this function is understood, yes he is the method to read the data, two parameters are also slightly simple, a time-out, if you set to 1 that never timeout, and the second parameter is to distinguish between the read and other read flags, Usually we have a property that is tag when we design a control on a view.

Now our connection action is complete. Next is the interaction with the server processing, that is, read and write operations, communication is to transfer data after all.

Second, read

[Asyncsocket Readdatatolength:length_header withtimeout:-1 Tag:tag_header];

  Of course we can deliver multiple read and write operations without having to wait for the previous completion.

  [Asyncsocket readdatatolength:length_header withtimeout:-1 tag:tag_response_body ];

This reads the request automatically into the queue, and when the socket is connected, the request is automatically executed. After this read operation is complete, the socket:didreaddata:withtag: will be called.

-(void)Socket(Gcdasyncsocket*)SenderDidreaddata:(NSData*)DataWithtag:(Long)Tag{If(Tag==Tag_header){IntBodylength=[SelfParseheader:Data];[SocketReaddatatolength:BodylengthWithtimeout:-1 tag:tag_response_body; } else if  (tag == span class= "n" >tag_response_body) {//Process the RESPONSE [self handleresponsebody:data; //Start reading the next response [socket  Readdatatolength:headerlength withtimeout:-1 Span class= "NL" >tag:tag_fixed_length_header; }}             /span>                

Write (same as read usage.) )

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{    if(tag ==TAG_HEADER)     NSLog(@"TAG_HEADER request sent");  elseif (tag ==TAG_BODY)     NSLog(@"TAG_BODY request sent");}

iOS Development--gcdasyncsocket

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.