Analysis on network programming for iOS development (I)

Source: Internet
Author: User
Tags call back file transfer protocol

The iPhone contains many frameworks and libraries, from the underlying sockets to different layers of encapsulation, you can easily add network functions to the program.

(1) BSD socket. The underlying socket, which is a common API for UNIX network development. If you port programs from other systems and the program uses BSD sockets, the Network part can continue to use these Apis.

(2) cfnetwork framework. Cfnetwork is also relatively underlying and is an extension of BSD sockets. It is a C language library, which is based on BSD sockets and provides abstraction of network protocols. These abstractions make it easier for users to operate sockets and process various network connections .. It integrates run-loop, so you do not need to implement the event loop yourself using cfnetwork. Cfnetwork also includes the implementation of some network protocols (such as HTTP and FTP), which can be used directly without understanding the details of these protocols.

(3) The foundation framework is a library based on objectice-C language. It provides object-oriented abstraction for cfnetwork APIs.

(4) cfurl (C)/nsurl (objective-C) is a high-level API that provides a simple way to download files or other resources from web and FTP servers. Cfurl is part of the cfnetwork and nsurl is part of the foundation.

(5) cfnetservices/nsnetservices provides methods for registering and discovering network services using bonjour.

In short, cfnetwork framework and foundation framework are the two most powerful libraries, which are relatively low-level and efficient, and provide rich interfaces.




As a basic component of network communication, sockets provide endpoints for two-way process communication between different hosts. If the phone number is used, the two parties can establish a dialogue only when one party calls the other. Through socket programming, the program can skip complex underlying network protocols and structures and directly compile platform-independent applications. Currently, sockets have gradually become a common interface for network programming. A socket exists in a specific communication domain (that is, a protocol family). Only a socket belonging to the same protocol family can establish a conversation. Generally, only sockets of the same type can transmit data to each other unless supported by the communication protocol. There are two main types of slave sockets: stream socket (TCP) and datagram socket (UDP ). Streaming socket (sock_stream): This type of socket provides connection-oriented, reliable, error-free data transmission service, and the data sent is accepted in order. All data transmitted using this socket is considered as a continuous byte stream and has no length limit. This method is applicable to applications that require strict data stability, correctness, and sending/receiving sequence. TCP uses this type of interface, but it occupies a relatively high line. The implementation of stream sockets is not uncommon, such as remote Logon (Telnet) and file transfer protocol (FTP. Datagram socket (sock_dgram): A datagram socket provides connectionless services. It sends data independently in the form of data packets (the length of the data packet cannot exceed 32 KB). It does not provide correctness checks or guarantee the sending sequence of each data packet, therefore, data re-transmission and loss may occur, and the order of acceptance is determined by the specific route. However, the implementation of datagram has a low share of network lines. NFS (Network File System) uses this type of socket. In the TCP/IP protocol family, UDP (user‑ramprotocol) uses this type of interface.


1. cfsocket

Cfsocket is an abstract encapsulation of BSD sockets. It provides almost all functions of BSD sockets and integrates run-loop. Cfsocket can process any type of socket, not just stream socket.

(1) create a cfsocket

The common methods are cfsocketcreate and cfsocketcreatewithnative.

The cfsocketcreate method declaration is as follows:

Cfsocketref cfsocketcreate (

Cfallocatorref Allocator, // specify the memory Distributor Type for creating a new socket. The default distributor can be used to pass in null or kcfallocatordefault. Generally, the default value is enough.

Sint32 protocolfamily, // specifies the protocol family of the socket. Pf_inet is used by default, that is, IPv4. Specify pf_inet6 to use the IPv6 protocol.

Sint32 sockettype, // socket type, sock_stream or sock_dgram.

Sint32 protocol, // The protocol used by the socket, ipproto_tcp or ipproto_udp. This option must be consistent with the socket type. If sockettype is sock_stream, the default value is ipproto_tcp. Otherwise, ipproto_udp is used ).

Cfoptionflags callbacktypes, // run-loop provided by cfsocket can call back the specified function when a specific part occurs. This parameter uses a bitmask. Therefore, you can use bitwise OR to specify multiple types. Apple defines some types as enumeration values as follows:

Enumerated Value

Enum cfsocketcallbacktype {

Kcfsocketnocallback = 0,

Kcfsocketreadcallback = 1,

Kcfsocketacceptcallback = 2,

Kcfsocketdatacallback = 3,

Kcfsocketconnectioncallback = 4,

Kcfsocketwritecallback = 8


Typedef Enum cfsocketcallbacktype;



Cfsocketcallback callout, // specify the callback function. When one of the specified event types occurs, the function is called. In this way, you do not have to write the loop to wait for the connection and send data.

Const cfsocketcontext * context // data structure for storing socket-related information, which can contain custom data. The function copies the content, so the memory to which the parameter points does not need to be retained after the function is called. It can be null.


Cfsocketcreatewithnative method, you can use an existing BSD socket to create a crsocket,

Cfsocketref cfsocketcreatewithnative


Cfallocatorref Allocator,

Cfsocketnativehandle sock,

Cfoptionflags callbacktypes,

Cfsocketcallback callout,

Const cfsocketcontext * Context



2. Socket Functions

After cfsocket is created, you can use a series of functions provided by cfsocket. Through the cfsocketnative function, you can also operate on the underlying BSD socket. The following functions are commonly used in cfsocket.

(1) cfsocketgetnative returns the system socket, usually int type. To obtain this socket, you can use the native socket operation of the UNIX system. Call the setsockopt function.

(2) cfsocketconnecttoaddress is used to connect a socket to a listening socket (server ).

(3) cfsocketcopyaddress: The cfsocket address returned to know which IP address the socket is listening.

(4) cfsocketcopypeeraddress: Obtain the address of the remote Socket connected to the cfsocket.

(5) cfsocketcreaterunloopsource creates a cfrunloop for cfsocket.

(6) cfsocketsenddata: The cfsocket, the address (null is sent to the address already connected to the socket), the data to be sent (cfdataref type), and the timeout time. The returned values include kcfsocketsuccess, kcfsocketerror, and kcfsockettimeout.


3. Callback Function


Function Type Definition

Typedef void (* cfsocketcallback )(

Cfsocketref s,

Cfsocketcallbacktype callbacktype,

Cfdataref address,

Const void * data,

Void * info




Function Declaration

Void callbacktest


Cfsocketref s,

Cfsocketcallbacktype callbacktype,

Cfdataref address,

Const void * data,

Void * info



Each callback function can obtain the following information. Some information varies depending on the type.

(1) cfsocket corresponding to the cfsocketrefs event, which can distinguish events generated by different sockets.

(2) cfsocketcallbacktype callbacktype identifies which event occurred.

(3) cfdataref address cfdata pointer containing the underlying sockaddr information. The remote address that can be connected to through the socket obtained through this parameter. This parameter is provided only when the kcfsocketacceptcallback and kcfsocketdatacallback events occur.

(4) const void * data points to different data based on the callback type. For the kcfsocketdatacallback type, this parameter is of the cfdataref type and contains the received data. For the accept type, this parameter is the pointer to the cfsocketnativehandle. For the kcfsocketconnectcallback type, the connection fails in the background, this parameter is a pointer to the sint32 type error code. In other cases, this parameter is null.

(5) The Info member in the Void * info cfsocketcontext structure is custom data. Cfsocketcontext is specified when cfsocket is created.


4. cfsocketcontext

It is a struct containing custom data and some callbacks. Because cfsocket uses run-loop to asynchronously notify events, it is difficult to keep track of data related to each connection when many connections exist. Cfsocketcontext allows you to bind data of any type to the socket. Each callback function can obtain the data.


Struct cfsocketcontext


Cfindex version; // the version number of the struct, which must be 0.

Void * Info; // pointer to custom data, associated when cfsocket is created.

Cfallocatorretaincallback retain; // The retain callback of the info pointer, which can be null.

Cfallocatorreleasecallback release; // call back the release of the info pointer, which can be null.

Cgallocatorcopydescriptioncallback copydescription; // call back the copy description of the info pointer, which can be null.


Typedef struct cfsocketcontext;


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: 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.