Communication between IOS apps-local socket

Source: Internet
Author: User
Tags socket error htons

Before I saw an article about five ways to communicate between apps, it had URL Scheme,keychain,uipastedboard,uidocumentinteractioncontroller and local communication using sockets. The previous 4 kinds have been useful to, also relatively simple, a few lines of code. For the last one has been useless before (forgive me still a little white), so try to write today, here is recorded here to share with you.

Well, nonsense not much to say, to begin:

First of all, it is very simple, in fact, an app in the local port for the TCP bind and listen, another app in the local same port to connect, so that the establishment of a normal TCP connection, you can send what data to pass what data. Start by creating the service side:

1, first create a socket with the socket () function

/* * Socket returns an int value, 1 for creation failure * The first parameter indicates the protocol family/domain, usually af_inet (IPV4), Af_inet6 (IPV6), af_local * The second parameter specifies a set of interface types: Sock_stream, Sock_dgram, Sock_seqpacket, etc. * The third parameter specifies the appropriate transport protocol, such as TCP/UDP, which is generally set to zero using this default value */int SOCK = socket (af_inet, sock_stream, 0); if (sock = =-1) {  close (sock);  NSLog (@ "Socket error:%d", sock);
return;}

2, bind the machine address and port number

Address structure data, record IP and port number struct SOCKADDR_IN sockaddr;//declaration using Protocol sockaddr.sin_family = af_inet;//get native IP, convert to char type const CHAR *ip = [[self getipaddress] cstringusingencoding:nsasciistringencoding];//assigns IP to struct, inet_addr () The function is to convert a dot-decimal IP to a long integer sockAddr.sin_addr.s_addr = inet_addr (IP);//Set port number, htons () is to convert an integer variable from host byte order to network byte order Sockaddr.sin_port = Htons (12345);/* The BIND function is used to associate a socket with an address, return an int value, 1 for failure * The first parameter specifies a socket, is the front socket function call return socket * The second parameter is the specified address * The third parameter is the size of the address data */int BD = Bind (sock, (struct sockaddr *) &sockaddr, sizeof (sockaddr ); if (BD = =-1) {  close (sock);  NSLog (@ "Bind error:%d", BD);  return;}

3, listen for the bound address

/* * The Listen function uses the active connection socket interface to become the connected interface, which allows the request of other processes to be accepted, returns an int value, 1 is the failure * The first parameter is the socket returned by the socket function * The second parameter can be understood as the maximum limit of the connection */int ls = Listen (sock,20); if (ls = =-1) {  close (sock);  NSLog (@ "Listen error:%d", ls);  return;}

 4, the following is waiting for the client connection, using accept () (because the Accept function will block the thread, while waiting for the connection will be stuck, it is recommended to put it in a child thread)

1, turn on a sub-thread nstread *recvthread = [[Nsthread alloc] initwithtarget:self selector: @selector (RecvData) Object:nil]; [Recvthread start];-(void) recvdata{//2, waiting for the client to connect//Declare an address structure, used to receive the address returned by the client after the    struct sockaddr_in recvaddr;//address size  socklen_t recv_size = sizeof (struct sockaddr_in);/* The Accept () function returns a new socket (Self.newsock) After the connection is successful, used to send and receive data before and after the client * The first parameter is the previously listening socket, which is a local variable, now needs to be changed to global * The second parameter is a result parameter, it is used to receive a return value, this return value specifies the address of the client * The third parameter is also a result parameter, which is used to receive the RECVADDR structure of the consignment, Indicate the number of bytes it occupies */self.newsock = accept (Self.sock, struct sockaddr *) &recvaddr, &recv_size);// 3, came here to represent already connected to a new client, the following can be sent to send and receive data, mainly used to send () and recv () function  ssize_t bytesrecv = 1;//return data byte size  char recvdata[ 128] = ""; Returns the data buffer//If one end disconnects, RECV returns immediately, Bytesrecv equals 0, and then the while loop executes, so the judgment equals 0 is to jump out while  (1) {  bytesrecv = recv ( self.newsocket,recvdata,128,0); RecvData for received data  if (Bytesrecv = = 0) {break    ;       }}  }

5, send data

-(void) sendmessage{        char senddata[32] = "Hello client";    ssize_t size_t = Send (Self.newsocket, SendData, strlen (SendData), 0);  }

The client side is mainly divided into: Create sockets, according to the IP and port number to obtain the server host address, and then connect, after the successful connection to the server to send and receive data, the following we look at the code.

1. Create sockets with the socket function as the server

int sock = socket (af_inet, sock_stream,0), if (sock = =-1) {  NSLog (@ "Socket error:%d", sock);  return;}

2, get the address of the host

NSString *host = [self getipaddress]; Gets the native IP address//returns the hostent struct pointer that contains host name and address information for the given host name struct hostent *remotehostent = gethostbyname ([host utf8string]); if ( Remotehostent = = NULL) {  close (sock);  NSLog (@ "cannot resolve server hostname");  return;}
Configure the IP address and port number of the host to which the socket will be connected for the Connect () function struct in_addr *remoteinaddr = (struct in_addr *) remotehost->h_addr_list[0]; struct sockaddr_in socktpram;socketpram.sin_family = af_int;socketpram.sin_addr = *remoteinaddr;socketpram.sin_port = Htons ([Port Intvalue]);

3, connect the host using the Connect () function

/* * The Connect function is typically used for client resume TCP connection, connection to the host of the specified address, function returns an int value, 1 for failure * The first parameter is the socket created for the socket function, which represents the socket to connect to the specified host * The second parameter is socket sock the host address and port number to which you want to connect * The third parameter is the host address size */int con = connect (sock, (struct sockaddr *) &socketpram, sizeof (SOCKETPRA m)); if (con = =-1) {  close (sock);  NSLog (@ "Connection failed");  return;} NSLog ("Connection succeeded"); Come this represents the connection success;

4, you can send and receive data after the connection is successful.

-(Ibaction) SendData: (ID) Sender {    //Send data    char senddata[32] = "Hello service";    ssize_t size_t = Send (Self.sock, SendData, strlen (SendData), 0);    NSLog (@ "%zd", size_t);} -(void) recvdata{    //accepts data, placed on sub-thread    ssize_t bytesrecv =-1;    Char recvdata[32] = "";    while (1) {            bytesrecv = recv (self.sock, RecvData, 0);        NSLog (@ "%zd%s", bytesrecv,recvdata);        if (Bytesrecv = = 0) {break            ;        }}    }

Well, it's OK to use the socket to make two app communications locally. The first time to write a blog, one is to record their own experience, and the second is to share with you, the text of the wrong place I hope you can point out. Finally attached to the demo address, two items, interested people can come down to try. https://pan.baidu.com/s/1nvcvC8p

Communication between IOS apps-local socket

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.