BSD Socket in iPhone Development

Source: Internet
Author: User
Tags htons

IPhone DevelopmentMediumBSD SocketEasy Learning is the content to be introduced in this article, mainly to learnIphone DevelopmentThread learning. In progressIphone DevelopmentCommunication programs must be usedSocketCommunication, except for the CFSocketIn addition to class interfaces, we can alsoBSD SocketThis article briefly introduces how to develop communication programs.BSD SocketI think it is a good entry-level article, so I will share it on the blog:

When you enter the mysterious world of UNIX, you will immediately find more and more things hard to understand. For most people, BSD (Berkeley Software Distribution, Berkeley Software suite is a Unix derivative system developed and released by UC Berkeley between 1977 and 1995) socket is one of them. This is a very short tutorial to explain what they are, how they work, and give some simple code to explain how to use them.

Analogy (what is socket ?)

Socket is a BSD Method for inter-program communication (IPC, Internet Process Connection. This means that the socket is used to allow a process to communicate with other processes, just as we communicate with others by phone.

It is quite appropriate to use telephone to describe socket in the future.

Install your new phone number (how to listen ?)

To receive a call from someone else, first install a call. Similarly, you must first establish a socket to listen on the line. This process involves several steps. First, you need to create a new socket, just like installing a phone number first. The socket () command is used to complete this task.

Because sockets has several types, you need to specify the type you want to establish. You need to select the socket address format. Just as the telephone has two forms of audio and pulse, socket has two most important options: AF_UNIX and IAF_INET. AF_UNIX recognizes sockets like UNIX pathnames. This form is useful for IPC on the same machine. AF_INET uses the address format of four decimal numbers separated by dots like 192.9.200.10. In addition to the machine address, you can also use the port number to allow multiple AF_INET sockets on each machine. Here we will focus on the AF_INET method, because it is very useful and widely used.

The other parameter you must provide is the socket type. Two important types are SOCK_STREAM and SOCK_DGRAM. SOCK_STREAM indicates that the data passes through socket like a forward stream. SOCK_DGRAM indicates that the data is in the form of a datagram rams. We will explain SOCK_STREAM sockets, which is common and easy to use.

After a socket is created, we need to provide the socket listening address. Just like you need a phone number to pick up your phone. Bind () function to handle this problem.

SOCK_STREAM sockets forms a queue for connection requests. If you are busy processing a connection, other connection requests will wait until the connection is processed. The listen () function is used to set a maximum of five requests that are not rejected ). Generally, you are advised not to use the listen () function.

The following code describes how to use the socket (), bind (), and listen () functions to establish a connection and accept data.

 
 
  1. int establish(unsigned short portnum)  
  2. { char   myname[MAXHOSTNAME+1];  
  3.   int    s;  
  4.   struct sockaddr_in sa;  
  5.   struct hostent *hp;  
  6.   memset(&sa, 0, sizeof(struct sockaddr_in));  
  7.   gethostname(myname, MAXHOSTNAME);            
  8.   hp= gethostbyname(myname);                    
  9.   if (hp == NULL)                              
  10.     return(-1);  
  11.   sa.sin_family= hp->h_addrtype;                
  12.   sa.sin_port= htons(portnum);                  
  13.   if ((s= socket(AF_INET, SOCK_STREAM, 0)) < 0)  
  14.     return(-1);  
  15.   if (bind(s,&sa,sizeof(struct sockaddr_in)) < 0) {  
  16.     close(s);  
  17.     return(-1);                                
  18.   }  
  19.   listen(s, 3);                                
  20.   return(s);  

After the socket is created, you have to wait for the socket to be called. The accept () function is used for this purpose. Calling accept () is the same as initiating a call after the phone rings. Accept () returns a new socket to the caller.

The following code demonstrates how to use it.

 
 
  1. int get_connection(int s)  
  2. { int t;                    
  3.   if ((t = accept(s,NULL,NULL)) < 0)    
  4.     return(-1);  
  5.   return(t);  

Different from the phone number, you can accept the call when you process the previous connection. Therefore, fork is generally used to process each connection. The following code demonstrates how to use establish () and get_connection () to process multiple connections.

 
 
  1. #include          
  2. #include   
  3. #include   
  4. #include   
  5. #include   
  6. #include   
  7. #include   
  8. #include   
  9. #include   
  10. #define PORTNUM 50000  
  11. void fireman(void);  
  12. void do_something(int);  
  13. main()  
  14. { int s, t;  
  15.   if ((s= establish(PORTNUM)) < 0) {    
  16.     perror("establish");  
  17.     exit(1);  
  18.   }  
  19.   signal(SIGCHLD, fireman);            
  20.   for (;;) {                            
  21.     if ((t= get_connection(s)) < 0) {  
  22.       if (errno == EINTR)              
  23.         continue;                      
  24.       perror("accept");                
  25.       exit(1);  
  26.     }  
  27.     switch(fork()) {                    
  28.     case -1 :                          
  29.       perror("fork");  
  30.       close(s);  
  31.       close(t);  
  32.       exit(1);  
  33.     case 0 :                            
  34.       close(s);  
  35.       do_something(t);  
  36.       exit(0);  
  37.     default :                          
  38.       close(t);                        
  39.       continue;  
  40.     }  
  41.   }  
  42. }  
  43. void fireman(void)  
  44. {  
  45.   while (waitpid(-1, NULL, WNOHANG) > 0)  
  46.     ;  
  47. }  
  48. void do_something(int s)  
  49. {  

Dialing (how to call socket)

Now you should know how to establishSocketTo accept the call. So how to call it? Like a phone number, you must have a phone number first. Use the socket () function to do this, just like creating a socket for listening.

InSocketYou can use the connect () function to connect to the listening socket. Below is a piece of code.

 
 
  1. int call_socket(char *hostname, unsigned short portnum)  
  2. { struct sockaddr_in sa;  
  3.   struct hostent     *hp;  
  4.   int a, s;  
  5.  
  6.   if ((hp= gethostbyname(hostname)) == NULL) {  
  7.     errno= ECONNREFUSED;                        
  8.     return(-1);                                  
  9.   }  
  10.  
  11.   memset(&sa,0,sizeof(sa));  
  12.   memcpy((char *)&sa.sin_addr,hp->h_addr,hp->h_length);  
  13.   sa.sin_family= hp->h_addrtype;  
  14.   sa.sin_port= htons((u_short)portnum);  
  15.  
  16.   if ((s= socket(hp->h_addrtype,SOCK_STREAM,0)) < 0)    
  17.     return(-1);  
  18.   if (connect(s,&sa,sizeof sa) < 0) {                    
  19.     close(s);  
  20.     return(-1);  
  21.   }  
  22.   return(s);  

This function returns a socket that can flow through data.

Conversation (how to talk through sockets)

Now you have established a connection between the two parties that want to transmit the data. Read () and write () functions. In addition to the difference between socket reading and writing and file reading and writing, it is the same as processing common files. The difference is that you generally cannot get the data you want. So you need to keep repeating to the arrival of the data you need. A simple example: Read data to the cache.

 
 
  1. int read_data(int s,      
  2.               char *buf,  
  3.               int n        
  4.              )  
  5. { int bcount;  
  6.   int br;      
  7.   bcount= 0;  
  8.   br= 0;  
  9.   while (bcount < n) {              
  10.     if ((br= read(s,buf,n-bcount)) > 0) {  
  11.       bcount += br;                  
  12.       buf += br;                    
  13.     }  
  14.     else if (br < 0)                
  15.       return(-1);  
  16.   }  
  17.   return(bcount);  

You can write data for the same function.

Suspend (end)

Like when you talk to someone by phone, you need to close the connection between sockets. Generally, the close () function is used to close socket connections on each side. If one side is disabled while the other side is writing data to it, an error code is returned.

The language of the world language is very important)

Now you can contact the machine, but be careful with what you said. Many machines have their own dialects, such as ASCII and EBCDIC. The more common problem is the byte order. Unless you have always transmitted text, you must pay attention to this problem. Fortunately, people have found a solution.

Long ago, people argued which order was more "correct ". Now it is necessary to have corresponding functions for conversion. There are htons (), ntohs (), htonl (), and ntohl (). Before transmitting an integer data, convert it.

 
 
  1. i= htonl(i);  
  2. write_data(s, &i, sizeof(i)); 

After reading the data, change it back.

 
 
  1. read_data(s, &i, sizeof(i));  
  2. i= ntohl(i); 

If you keep sticking to this habit, you will have fewer chances of making mistakes than others.

The future is under your control (next step ?)

With what we have discussed, you can write your own communication program. Like all new things, it is best to see what others have done. There are many things about BSD socket for reference.

Please note that there is no error check in the example, which is very important in the "real" program. You should pay full attention to this.

Summary: AboutIPhone DevelopmentMediumBSD SocketI hope this article will help you with the ease of learning!

Related Article

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.