IOS app Communication's local socket example _ios

Source: Internet
Author: User
Tags socket error strlen port number htons

I've seen an article about five ways to communicate between apps, which have URL Scheme,keychain,uipastedboard,uidocumentinteractioncontroller and use sockets for local communication. The first 4 kinds of things have been useful, but also relatively simple, a few lines of code. For the last one has never been used before (forgive me is a little white), so try to write today, here is recorded here and share with you.

Okay, nonsense don't say much, start:

First of all, the principle of it, in fact, is very simple, an app in the local port for TCP bind and listen, and another app on the local same port to connect, so that a normal TCP connection, you can want to pass any data on what data. The following starts by creating a service-side:

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


 * * Socket returns an int value,-1 for Create failure
 * The first parameter indicates the protocol family/domain, usually with af_inet (IPV4), Af_inet6 (IPV6), af_local
 * The second parameter specifies a set of interface types: Sock_stream,sock_dgram, Sock_seqpacket, and so on
 * The third parameter specifies the corresponding transport protocol, such as TCP/UDP, which is generally set to 0来 using this default value.
int sock = socket (af_inet, sock_stream, 0);
if (sock = = 1) {Close
 (sock);
 NSLog (@ "Socket error:%d", sock);<br> return;
}

2, bind this machine address and port number

Address structure body data, recording IP and port number
struct sockaddr_in sockaddr;
The protocol used by the declaration
sockaddr.sin_family = af_inet;
Gets the native IP, converts to a char-type
const char *IP = [[self getipaddress] cstringusingencoding:nsasciistringencoding];
assigning IP to a struct, the inet_addr () function converts a dotted decimal IP to a long integer number
sockAddr.sin_addr.s_addr = inet_addr (IP);
Set the port number, htons () is the conversion of integer variables from host byte order to network byte order
sockaddr.sin_port = htons (12345);
 /* * Bind function to associate a socket with an address, return an int value,-1 for failure
 * The first parameter specifies a socket, that 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, listening for binding addresses


 * * Listen function uses the active connection socket interface to become the connected interface, so that it can accept requests from other processes, return an int value,-1 is a 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 a connection waiting for the client, using accept () (because the Accept function blocks the thread, it is stuck while waiting for the connection, so it is recommended to put it in a child thread)

1, open a child 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 that is used to return the address 
 struct sockaddr_in recvaddr at the back of the receiving client;
Address size
 socklen_t recv_size = sizeof (struct sockaddr_in);
 * * 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 socket that was previously listening, the local variable, and now it needs to be changed to the global
 * The second parameter is a result parameter that is used to receive a return value that specifies the address of the client
 * The third parameter is also a result parameter, which is used to receive the consignment of the RECVADDR structure, indicating the number
of bytes it occupies. Self.newsock = Accept (Self.sock, (struct sockaddr *) &recvaddr, &recv_size);
3, came here on behalf of already connected to a new client, the following can send and receive data, mainly used to send () and recv () function
 ssize_t bytesrecv =-1;//return data byte size
 Char RECVDATA[128] = ""; Return data buffer
//If one end is disconnected, RECV returns immediately, Bytesrecv equals 0, then the while loop executes, so the judgment equals 0 is skipped while
 (1) {
 BYTESRECV = Recv (self.newsocket,recvdata,128,0); RecvData for received data
 if (Bytesrecv = = 0) {break
 ; 
 }
}}

5, send the 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 IP and port number to obtain the server's host address, and then connect, after successful connection to the server to send and receive data, the following we look at the code.

1, as with the server to create sockets with the socket function

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 structure pointer that contains the host name and address information for a given host name
struct hostent *remotehostent = gethostbyname ([host Utf8string]);
if (remotehostent = = NULL) {Close
 
 (sock);
 NSLog (@ "Unable to resolve server host name");
 return;
} <br>//configures the IP address and port number that the socket will connect to the host, 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


 /* * Connect function is usually used for client resume TCP connection, connect the host of the specified address, function return an int value,-1 for failure
 * The first parameter is a socket created by the socket function to connect to the specified host
 * The second parameter is the socket sock the host address and port number to which you want to connect
 * The third parameter is host address size/
int con = connect (sock, (struct sockaddr *) & Socketpram, sizeof (Socketpram));
if (con = = 1) {Close
 (sock);
 NSLog (@ "Connection failed");
 return;
}
NSLog ("connected successfully"); Come to 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{
 //acceptance data, placed in the child 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
   ;
  }}
 }

All right, I'm going to use the socket for two apps on the local phone. The first time to write a blog, one is to record their own experience, and the second is to share with you, the text has the wrong place I hope you can point out. Finally attached demo address, two items, interested everyone can come down to try.

https://pan.baidu.com/s/1nvcvC8p

The above is the iOS app communication-local socket data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!

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.