Gcdasyncsocket class Library, iOS under the use of TCP communication experience

Source: Internet
Author: User

About the use of the socket to communicate in iOS technical article also promised a long time, today is a debt repayment days, online although many introduced Asyncsocket or gcdasyncsocket articles, but in fact, so one or two of the majority are reproduced, so I righteous words, The impassioned criticism of their irresponsible attitude, learning, not to learn for themselves, is to share with you. The sharing of technology is conducive to the overall industry progress, but also can make their own more in-depth and comprehensive understanding.

In the previous article we talked about the TCP communication protocol, and it is also a more detailed introduction and description, about the principle of TCP communication here we do not repeat, if necessary crossing can self-read I wrote "IOS, Android im Voice chat development part of the experience--Network Foundation "article.

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 complex, the main point is in the use of this kind of library when I have some experience and understanding, if there is something wrong to look crossing pointing. First of all 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. Of course, before this, we should add the Cgdasyncsocket. h file and the. m file to our project and include the. h header file where you need to use the socket connection. I don't think I need to retell it. (Then you hooves hooves said half a day why AH Hello! )。 The specific 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 so that we can do it immediately, and our socket is currently in the program 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, we are transitioning from the HTTP protocol to the TCP protocol (although this article does not teach you how to architect a server on iOS.) ), but not the first, the first shift is to remember that we are 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 *err;

[Socket connecttohost:@ "192.168.10.111" [email protected] "60000" error:&err];

if (err! = nil)

{

NSLog (@ "%@", err);

}

The code is a little bit longer than before, but essentially completely uncomplicated, we just declare a pointer to the error message, and then use the object created earlier to call his connection method, the first parameter is not difficult to see is an IP, the second parameter is a port, if it does not understand what is the IP and port, Let's go and see what I've written before in the beginning of the Web Foundation article. The last one is out of the argument, if there is an error in the connection, the method will point the pointer to a specific error message, and finally we will determine whether the pointer we created the error message is still pointing to null, if it is not pointing to null then an error occurred in the process of our connection, print the error message ~ Remember, however, that the error message here is not a reflection of all the errors you make 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 Many people who is exposed to marijuana need to casino on Line get quick THC antioxidants due to their employer. *) host Port: (uint16_t) port

This method is the delegate method after the successful connection to the server. About the delegate how to use I do not repeat here and this article of the relationship is not very small, but for you to look after a suggestion, but also I just corrected a coding error habit, before I met all the delegates where I will directly set the current class object to the delegate processing object, and follow the delegation protocol extension Code, The downside of this is obvious, and the confusion between the display layer and the logic layer is on the one hand, and the other is that once you need to use too many delegates, it will cause a lot of unnecessary code to accumulate in a class, and we can easily directly use some in-class member properties or even private members in the delegate method. In fact, this practice is very bad, because this is the most likely to make the logic chaos, processing the delegate should be separate in the background of the logic, if you need some necessary data transfer should also take the property to listen, or even notification, and so on, rather than directly in the display layer to write logic code to implement. This increases the coupling of the code and makes it more complicated to handle the delegate object when switching objects, even if the exact same code should be copied and pasted. So my advice to you is to write a delegate class individually, set a member pointer to that class type in each class, set the delegate to a dedicated delegate object to handle, which is not only more efficient, more readable, easier to maintain, and more consistent with object-oriented programming ideas.

Back to the Gcdasyncsocket use of the explanation, in this delegate method, we can take a socket object a server IP and a port number, you can handle everything after the connection is established should be executed immediately after the thing, such as communication with the server to confirm the connection side to avoid other people through the IP and port arbitrary and your server communication, such as open heartbeat packet sent, so that the server has been able to confirm your presence. Whatever you do, you and the server writer beforehand agreed, like data transmission format What, if there is no face to contract I firmly believe that he must also give you a document or something, otherwise your work will be difficult to follow. But no matter what you're going to do here and what you're going to do, 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? Don't panic, according to the first reaction you see this function to understand, 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. If you have done Web development, then you should know the ID on the HTTP tag, if you have done some desktop-level development, your control may have an ID or a property of index or tag to distinguish the controls, yes this tag and the other tag effect basically the same.

We can understand that the socket before opening is a huge door, after opening the door (that is, after the connection) is a spacious channel, through this channel to reach the target server, or connected to the client, both sides are the same. Whether we are sending data or reading data is a gate to the door of the guard and the postman, we can read the data method as a doorman, and send data to the person as a postman, yes, the server and the client are the same, we will send a postman to the other end of our connection, But if you do not order your doorman to go to the door in the mail box, then your postman will pretend not to see the postman, and then sound asleep, well, it seems that these guards have no sense of responsibility is not, in fact, they also have difficulties, because this is the original designer gave them orders, Do not receive orders absolutely do not go out, in case received is the King Kong gourd Baby HD Complete the seeds how to do! Ok so, in order to avoid our mail is not missed, so after the establishment of a connection to let a doorman run to the door waiting for it ~ slow, in case I need to send a lot of doorman I can't tell what they should do, in fact, they have been you assigned the work number, this work number is tag.

Now our connection action is complete, the next thing we have to do is only two things, the first to send data when sending the postman, and when the doorman received the message on our mobile phone in accordance with the information of the doorman to respond. Wait, it's like something's missing. Delegate, let's take a look at the read and write the delegate, read the delegate is the doorman to receive information reports, write the delegate is the postman will send the message after the reply:

-(void) Socket: (Gcdasyncsocket *) sock didreaddata: (NSData *) data withtag: (long) tag

-(void) Socket: (Gcdasyncsocket *) sock Didwritedatawithtag: (long) tag

Okay, let's see what we can get in these delegates, first the read delegate, a socket object, a read data, and a "janitor's work number," Well, that's probably all we need, yes, that's enough, don't complain about the data type of the second parameter, To know the first time when the data is only a byte array ah, has converted you to NSData object you have to learn to be thankful Ah, who let you to use socket transmission, this is deserved, so change how to read the conversion to parse the data you need to communicate with the server writer. In addition, you need to know more about how to convert nsdata into various data or files. If you don't know what to do, I can't help you here, because I can't do it. In this article, you should know that every article is long enough. But don't be discouraged. Baidu and Google can certainly help you ~

Next we look at the "Postman's commission," Um, a Socket object, a tag well, yes, ah ah, slow, as if it is not very right ah, I came to see, where is wrong, oh right! The data Sent! Why not! Hey, it's not right. Obviously I sent the data I have to do, I have a work number I do not know what is sent. What's wrong with that? Oh! It's a name! Our data transmission is accepted can be read and sent usually we should write the word "send", why is this write? Write? Yes, it writes, writes data to the TCP traffic stream. TCP communication protocol is a transport layer communication protocol based on Byte stream, and its data transmission form is also in the form of streaming, and I feel that in the process of using gcdasyncsocket we can very well experience the concept of flow, First of all, why is this type of TCP transmission called a stream instead of a packet, as in UDP? Stream is written and read out of the concept, we can put the entire TCP communication connection as a water-free river, of course, because he has no water so you can call it a ditch, and write to it is to the river into the water, the written data will flow to the other end of the same water. Reading is to take water from the river, as long as the reading movement continues, and there is water in the river, then we can continue to fetch data, whether there is water in the river you do not read it or you read the river and no water will cause the same seemingly identical reaction is no data return, So in many cases we have to deal with more of the logic of receiving data. As we are currently using the method is a more crude and effective method-once opened the connection to read the action will never cease.

Next we also remember a key issue when using TCP to stream data, and the data does not fragment itself. Yes, like pouring water into the river again, the data will be the same as the water into a whole, in other words, the data in the TCP transmission itself is no beginning or end of the point, if I first write to the data stream two people's chat record, the first sentence is "Hello", the other side replied "bad", Results sent to the server, the server read the information is "Hello bad", the same similar situation will happen a lot more common than I cite this example, such as I first sent a piece of audio, and sent a picture, and sent a paragraph of text, the last server received a voice and the letter of a static picture. In fact, more than I said, because there is no boundary between the bytes, so the character, text, audio, we can not determine how long they each, random interception, will only lead to the inability to parse into pictures, text and audio, so how to define the boundary between the data is you start using the TCP protocol after another problem. You can use a fixed array of byte arrays to distinguish between the beginning and the end, or you can add a special delimiting character to all the strings to differentiate between commands and operations.

If you see the crossing here to use Gcdasyncsocket to write a server side, and use it to accept the client's data, such as the transmission of some audio, pictures and so on from the byte unit appears to be a long string of data, you will find that the server side of the program is a paragraph, yes, But I did not deceive you, the TCP protocol does not differentiate you from sending data to the tail and ends, is divided into segments of knowledge gcdasyncsocket in order to ensure that not the usual mobile internet can be the same as the safe transfer of data, so that all of your data written to the stream is divided into a paragraph of content, So please understand correctly what I said at the beginning of the previous paragraph, "Data is not segmented by itself." "This sentence, don't be serious OH pro ~

Write here, the basic operation of Gcdasyncsocket and its core ideas are all finished, for the thought part of the author personally understand, if there is a lack or differences of opinion, welcome to exchange ideas to learn from each other, thank you for your reading.

This entry was published by Sutersing in the IOS, Mac category directory. Add a pinned link to your Favorites folder.

Gcdasyncsocket class Library, iOS under the use of TCP communication experience

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.