Analysis of socket usage and precautions in Android NDK

Source: Internet
Author: User
Tags htons

The entire process of using socket in Android NDK is divided into the following parts:
Part 1: Create a socket and bind the IP address and port
Copy codeThe Code is as follows: # include <sys/select. h>
# Include <sys/socket. h>
# Include <arpa/inet. h>
# Define MAX_DATA_BUF_LEN 10240.
Int sd = INVALID_SOCKET;
Sockaddr_in addr_org; // The sender address.
Sd = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); // create a socket
Addr_org.sin_family = AF_INET;
Addr_org.sin_addr.s_addr = inet_addr ("192.128.0.1"); // the IP address of the sender.
Addr_org.sin_port = htons (8080); // sending end Port
Bind (sd, (struct sockaddr *) & (addr_org), sizeof (struct sockaddr_in); // bind the IP address and port

Part 2: send data
Copy codeThe Code is as follows: sockaddr_in addr_dst; // The acceptor address.
Addr_dst.sin_family = AF_INET;
Addr_dst.sin_addr.s_addr = inet_addr ("192.128.0.2"); // acceptor IP Address
Addr_dst.sin_port = htons (8080); // acceptor Port
... // Generate the data to be sent to SendDataBuff. The length is ulLen.
Sendto (sd, SendDataBuff, ulLen, 0, (struct sockaddr *) & (addr_dst), sizeof (sockaddr_in); // send data in SendDataBuff

Part 3: receiving data in a thread (non-blocking)
Copy codeThe Code is as follows: void * SocketReceiveThread (void * pParam)
{
Fd_set fdset;
Struct timeval delayval;
Unsigned long lRetVal;
Delayval. TV _sec = 0;
Delayval. TV _usec = 5000;/* 5 ms latency */
While (! End_flag)
{
FD_ZERO (& fdset );
FD_SET (sd, & fdset );
LRetVal = select (sd + 1, & fdset, NULL, NULL, & delayval); // pay attention to the first parameter.
If (0 = lRetVal)
{
Continue;
}
Else if (SOCKET_ERROR = lRetVal)
{
Break;
}
Else if (FD_ISSET (sd, & fdset )! = 0)
{
Char RecvDataBuff [MAX_DATA_BUF_LEN]; // receives the data buffer.
Unsigned long ulLen = recvfrom (sd, RecvDataBuff, MAX_DATA_BUF_LEN, 0, NULL, NULL );
... // Process received data
}
}
}

Part 4: Disable socket
Close (sd );

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.