Cfsocket communication on iOS

Source: Internet
Author: User
Tags htons
Client: Import header file:
# Import <sys/socket. h>
# Import <netinet/in. h>
# Import <ARPA/inet. h>
# Import <unistd. h>

1. Create a connection
Cfsocketcontext sockcontext = {0, // the version of the struct, which must be 0
Self,// Data of any pointer, which can be used when the cfsocket object is created. This pointer is passed to all callback defined in the context.
 Null, // A retain callback defined in the pointer above. It can be null.
 Null, null };

Cfsocketref _ socket = (kcfallocatordefault, // allocate memory for the new object, which can be nil
 Pf_inet, // protocol family. If it is 0 or negative, the default value is pf_inet.
 Sock_stream, // socket type. If the protocol family is pf_inet, It defaults to sock_stream.
 Ipproto_tcp, // SOCKET protocol. If the protocol family is pf_inet and the Protocol is 0 or negative, ipproto_tcp is used by default.
 Kcfsocketconnectcallback, // Specifies the socket message type that triggers the callback function. For details, see callback types.
 Tcpserverconnectcallback, // The callback function triggered in the preceding case
 & Sockcontext // an object holding cfsocket structure information, which can be nil
 );

If (_ socket! = Nil ){
   Struct sockaddr_in addr4; // IPv4
   Memset (& addr4, 0, sizeof (addr4 ));
   Addr4.sin _ Len = sizeof (addr4 );
   Addr4.sin _ family = af_inet;
   Addr4.sin _ Port = htons (8888 );
   Addr4.sin _ ADDR. s_addr = inet_addr ([straddress utf8string]);// Convert the string address to a machine-recognized network address
   
   // Convert the address in the sockaddr_in struct to data
   Cfdataref address = cfdatacreate (kcfallocatordefault, (uint8 *) & addr4, sizeof (addr4 ));
   Cfsocketconnecttoaddress(_ Socket, // connected socket
 Address, // cfdataref type object that contains the remote address of the above socket
 -1// Connection timeout. If the value is negative, the connection is not attempted. Instead, the connection is placed in the background. If the _ socket message type is kcfsocketconnectcallbackWill trigger the callback function in the background when the connection is successful or fails.
 );

 Cfrunloopref crunref = cfrunloopgetcurrent ();// Obtain the loop of the current thread
   // Create a loop, but it is not actually added to the loop. You need to call cfrunloopaddsource
   Cfrunloopsourceref sourceref = cfsocketcreaterunloopsouRCE (kcfallocatordefault, _ socket, 0 );
   Cfrunloopaddsource (crunref, // running cycle
   Sourceref,// Added running cycle source, which will be retaken once
 Kcfrunloopcommonmodes// Added running cycle source Mode
   );
   Cfrelease (courceref );
}

2. Set the callback function
// Format of the socket callback function:
Static void tcpserverconnectcallback(Cfsocketref socket, cfsocketcallbacktype type, cfdataref address, const void * data, void * info ){
   If (Data! = NULL ){
       // When the socket is kcfsocketconnectcallbackIf the callback fails, an error code pointer is returned. Otherwise, null is returned.
       Nslog (@ "connection failed ");
       Return;
   }
   Tcpclient * client = (tcpclient *) Info;
   // Read the received data
   [Info performslectorinbackgrouNd: @ selector (readstream) withobject: Nil];
}

3. receive and send data
// Read the received data
-(Void) readstream {
   Char buffer [1024];
   NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];
   While (Recv (cfsocketgetnative (_ socket), // If the socket associated with the local machine has expired, return-1: invalid_socket
          Buffer, sizeof (buffer), 0 )){
       Nslog (@ "% @", [nsstring stringwithuf8string: Buffer]);
   }
}

// Send data
-(Void) sendmessage {
   Nsstring * stringtosend = @ "hello ";
   Char * Data = [stringtosend utf8string];
   Send (sfsocketgetnative (_ socket), data, strlen (data) + 1, 0 );
}

Server:

Cfsockteref _ socket;
Cfwritestreamref outputstream = NULL;

Int setupsocket (){
   _ Socket = cfsocketcreate (kcfallocatordefault, pf_inet, sock_stream, ipproto_tcp, kcfsocketacceptcallback, tcpserveracceptcallback, null );
   If (null ==_socket ){
     Nslog (@ "cannot create socket! ");
     Return 0;
   }
   
   Int optval = 1;
   Setsockopt (cfsocketgetnative (_ socket), sol_socket, so_reuseaddr, // allow reuse of local addresses and ports
(Void *) & optval, sizeof (optval ));
   
   Struct sockaddr_in addr4;
   Memset (& addr4, 0, sizeof (addr4 ));
   Addr4.sin _ Len = sizeof (addr4 );
   Addr4.sin _ family = af_inet;
   Addr4.sin _ Port = htons (port );
   Addr4.sin _ ADDR. s_addr = htonl (inaddr_any );
   Cfdataref address = cfdatacreate (kcfallocatordefault, (uint8 *) & addr4, sizeof (addr4 ));
   
   If (kcfsocketsuccess! = Cfsocketsetaddress (_ socket, address )){
     Nslog (@ "bind to address failed! ");
     If (_ socket)
            Cfrelease (_ socket );
     _ Socket = NULL;
  

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.