Android NDK and Java for local socket communication

Source: Internet
Author: User
Tags connect socket

With regard to the socket communication between Android applications and the framework, it is believed that friends who care about this issue have seen the article "Android uses sockets to make the underlying and framework communication" The drawback is that the author only posted some key snippets and did not release the source code. I still have a practical example of this, based on this, it is also convenient for everyone to learn.

First look at the effect, such as. I fill in the name "Potter", select the gender "Mr" and then click Send, the underlying socket receives the message and returns the message directly to me, I will return the result (Mr.potter) directly to show in result.

Write the socket server code to generate the executable script HTFSK.

#define SOCKET_NAME "HTFSK" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include < string.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys /wait.h> #include <sys/un.h> #include <cutils/sockets.h> #include <utils/Log.h> #include <     Android/log.h>int Main () {char log[200];    int connect_number = 6;    int fdlisten =-1, new_fd =-1;    int ret;    struct Sockaddr_un peeraddr;    socklen_t Socklen = sizeof (PEERADDR);    int numbytes;    Char buff[256];    This step is critical to get the socket Fdlisten = Android_get_control_socket (socket_name) configured in the init.rc named "HTFSK"; if (Fdlisten < 0) {sprintf (log, "Failed to get Socket" "Socket_name" ' errno:%d ", errno); __android_log_write (Android_lo G_debug, "Ftm_jni", log);    Exit (-1);            }//Start monitoring ret = Listen (Fdlisten, connect_number);    sprintf (log, "Listen result%d", ret);        __android_log_write (Android_log_debug, "Ftm_jni", log); if (Ret < 0) {perror ("listen");    Exit (-1);    }//wait for the socket client to start connection request NEW_FD = Accept (Fdlisten, (struct sockaddr *) &peeraddr, &socklen);    sprintf (log, "Accept_fd%d", new_fd);     __android_log_write (Android_log_debug, "Ftm_jni", log);        if (NEW_FD < 0) {sprintf (log, "%d", errno);         __android_log_write (Android_log_debug, "Ftm_jni", log);        Perror ("Accept error");    Exit (-1); The while (1) {//loop waits for the socket client to send the message __android_log_write (Android_log_debug, "Ftm_jni", "Waiting for receive"); if (numbytes        = recv (new_fd,buff,sizeof (Buff), 0)) ==-1) {sprintf (log, "%d", errno); __android_log_write (Android_log_debug, "Ftm_jni", log); Perror ("recv"); continue;}    Send a message receipt to the socket client if (send (New_fd,buff,strlen (buff), 0) ==-1) {perror ("send"), close (NEW_FD); exit (0);}    } close (NEW_FD);    Close (Fdlisten); return 0;}

3, write the client Java code. The core code is as follows:

Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.printwriter;import Android.net.localsocket;import Android.net.localsocketaddress;import Android.util.Log /** * Socket Client * * @author Lai_zs * @date: 2012-3-17 pm 12:15:09 */public class Socketclient {private final String SOCKET _name = "HTFSK";p rivate localsocket client;private localsocketaddress address;private Boolean isconnected = false;  private int connettime = 1;public socketclient () {client = new Localsocket (); address = new Localsocketaddress (Socket_name, LocalSocketAddress.Namespace.RESERVED); new Connectsocketthread (). Start ();}  /** * Send Message * @param msg * @return return message receipts from socket server */public string sendmsg (String msg) {if (!isconnected) {return ' Connect Fail ";} try {BufferedReader in = new BufferedReader (New InputStreamReader (Client.getinputstream ())); PrintWriter out = new PrintWriter (Client.getoutputstream ()); Out.println (msg); Out.flush (); return In.readline ();} catch (IOException e) {E. Printstacktrace ();} Return "Nothing Return";} /** * Asynchronous Connection socket, if the connection does not attempt to repeat the connection 10 times * * @author Administrator * */private class Connectsocketthread extends Thread {@Overri depublic void Run () {while (!isconnected && connettime <=) {try {sleep (1000); LOG.I ("Socketclient", "Try to connect socket; Connecttime: "+connettime); Client.connect (address); isconnected = true;} catch (Exception e) {connettime++;isconnected = false; LOG.I ("Socketclient", "Connect Fail");}}} /** * Close socket */public void closesocket () {try {client.close ();} catch (IOException e) {e.printstacktrace ()}}}

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.