IOS socket Programming (Getting started)

Source: Internet
Author: User
Tags sin socket error htons

1. C-based BSD socket (a common network interface in UNIX systems )

Feel BSD sockets easiest to understand, easiest to get started with, most flexible but most difficult to use, especially for large projects

Need to import header file

#import <sys/socket.h> #import <netdb.h>

Server-side

    int LISTENFD, CONNFD;    struct sockaddr_in servaddr;    Char buff[4096];    Long N;        int i=100; Create socket if ((LISTENFD = socket (af_inet, sock_stream, 0)) = =-1) {printf ("Create Socket Error:%s (errno:%d)        \ n ", Strerror (errno), errno);    Return    }//Initialize IP address memset (&servaddr, 0, sizeof (SERVADDR));    servaddr.sin_family = af_inet;    SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any); Servaddr.sin_port = htons (8088);//Bind the URL port if (Bind (LISTENFD, (struct sockaddr*) &servaddr, s) as the port URL requested by the client//        Izeof (servaddr)) = =-1) {printf ("Bind socket Error:%s (errno:%d) \ n", Strerror (errno), errno);    Return }//Listening URL port if (listen (LISTENFD) = =-1) {printf ("Listen socket Error:%s (errno:%d) \ n", Strerror (errno        ), errno);    Return    }//Accept data from the server printf ("======waiting for client ' s request======\n"); while (i>0) {if (CONNFD = Accept (LISTENFD, (struct sockaddr*) null, NULL))= =-1) {printf ("Accept socket Error:%s (errno:%d)", Strerror (errno), errno);        Continue        } n = recv (CONNFD, Buff, MAXLINE, 0);        Buff[n] = ' + ';        printf ("Recv msg from client:%s\n", buff);    Close (CONNFD); }//Close socket Close (LISTENFD);

Client

-(void) Senddatatoserverurl: (Nsurl *) url{int sockfd;    Char sendline[4096];    struct sockaddr_in servaddr;        NSString * host = [URL host]; Create socket if ((SOCKFD = socket (af_inet, sock_stream, 0)) < 0) {printf ("Create Socket Error:%s (errno:%d) \ n        ", Strerror (errno), errno);    Return }//Initialize IP address struct hostent * hostent = gethostbyname ([host utf8string]);//obtain IP information by domain name if (NULL = = Hostent        {NSLog (@ "Resolve Domain name failed");    Return        } struct in_addr * remoteinaddr = (struct in_addr *) hostent->h_addr_list[0];    memset (&servaddr, 0, sizeof (SERVADDR));    servaddr.sin_family = af_inet;    Servaddr.sin_port = htons (8088);        SERVADDR.SIN_ADDR = *remoteinaddr; Link TCP Server (based on IP address) if (Connect (sockfd, struct sockaddr*) &servaddr, sizeof (SERVADDR)) < 0) {printf ("Connec        T error:%s (errno:%d) \ n ", Strerror (errno), errno);    Return    }//Send string to the TCP server printf ("Send msg to server: \ n");Fgets (Sendline, 4096, stdin); if (Send (SOCKFD, Sendline, strlen (Sendline), 0) < 0) {printf ("Send msg Error:%s (errno:%d) \ n", Strerror (Errn        o), errno);    Return }//Closes socket close (SOCKFD);}

2.FCSocket interface more than BSD socket

Server-side and BSD sockets are a bit similar,

The client is completely different from the BSD socket, using an input/output stream.

Server-side

Receive message listener static void Handleconnect (Cfsocketref sock, Cfsocketcallbacktype type, cfdataref address, const void *data, void * Info) {NSLog (@ "received message");}    -(void) openfcsocket{//Create socket const Cfsocketcontext Socketctxt = {0, (__bridge void *) self, NULL, NULL, NULL};                                           Cfsocketref Cfsocket = cfsocketcreate (Kcfallocatordefault,                                           Pf_inet, Sock_stream,                                           Ipproto_tcp, Kcfsocketacceptcallback,        (cfsocketcallback) handleconnect,//receive information callback &socketctxt);        if (Cfsocket = = NULL) {NSLog (@ "Create socket failed");    Return    }//Initialize IP address struct sockaddr_in sin;    memset (&sin, 0, sizeof (sin));    Sin.sin_len = sizeof (SIN); sin.sin_family = af_inet; /* Address family */sin.siN_port = htons (8088);            /* Or a specific port */sin.sin_addr.s_addr= Inaddr_any;                                    Bind URL Port cfdataref sincfd = Cfdatacreate (Kcfallocatordefault,        (UInt8 *) &sin, sizeof (sin));    if (kcfsocketsuccess! = cfsocketsetaddress (Cfsocket, SINCFD)) {NSLog (@ "Bind URL port failed");            } cfrelease (SINCFD);                                                                  Add socket to run loop cfrunloopsourceref Socketsource = Cfsocketcreaterunloopsource ( Kcfallocatordefault, CFSOC    Ket, 0);                       Cfrunloopaddsource (Cfrunloopgetcurrent (), Socketsource, Kcfrunloopdefaultmode);}

Client

NSString *host = @ "127.0.0.1";    int port = 8088;    Create an input/output stream cfreadstreamref Readstream;    Cfwritestreamref Writestream;                                       Cfstreamcreatepairwithsockettohost (Kcfallocatordefault, (__bridge cfstringref) host,    Port, &readstream, &writestream);    Nsinputstream *inputstream = (__bridge nsinputstream *) Readstream;        Nsoutputstream *outputstream = (__bridge nsoutputstream *) Writestream; if (InputStream = = Nil | | outputstream = nil) {NSLog (@ "Stream creation failed!)        ");    return;    }//start the input/output stream [InputStream open];            [OutputStream Open];    Send data NSData *outgoingdatabuffer = [@ "testdata" datausingencoding:nsutf8stringencoding];    Nsinteger writtenbytes = [OutputStream write:outgoingDataBuffer.bytes maxLength:outgoingDataBuffer.length];        if (writtenbytes = =-1) {NSLog (@ "send failed");    Return } NSLog (@ "send success");

3. The Cocoaasyncsocket encapsulates the Cfsocket

Implements the TCP,UDP, joins the asynchronous thread, disconnects the heavy connection, Tls/ssl and so on, actually needs to implement in the development the thing.

If there's no time to reinvent the wheel, it's good to use such a third-party framework.



IOS socket Programming (Getting started)

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.