Use SOCKET in Android ndk

Source: Internet
Author: User
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
# 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; // sending end address SD = socket (af_inet, sock_dgram, ipproto_udp); // create socket timeout = af_inet; vertex = inet_addr ("192.128.0.1"); // sending end IP 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

Sockaddr_in addr_dst; // acceptor address addr_dst.sin_family = af_inet; receiver = inet_addr ("192.128.0.2"); // acceptor IP address receiver = 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)

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 special 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 data buffer unsigned long ullen = recvfrom (SD, recvdatabuff, max_data_buf_len, 0, null, null );... // process received data }}}

Part 4: Disable socket

close(sd);

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.