Android and native C use local socket for message transmission
Java source code:
// Import Java on the server side. io. bufferedreader; import Java. io. inputstream; import Java. io. inputstreamreader; import android.net. localserversocket; import android.net. localsocket; import android. util. log; public class socketlistener extends thread {@ overridepublic void run () {log. I (getclass (). getname (), "Run ()"); try {localserversocket Server = new localserversocket ("com. example. mysoftphone. localsocket "); While (tru E) {localsocket receiver ER = server. Accept (); log. I (getclass (). getname (), "server. Accept ()"); If (receiver er! = NULL) {inputstream input = Receiver. getinputstream (); inputstreamreader inputreader = new inputstreamreader (input); bufferedreader bufferreader = new bufferedreader (inputreader); string line = bufferreader. readline (); // string line1 = new string (line. getbytes ("UTF-8"); log. I (getclass (). getname (), line) ;}} catch (exception e) {log. E (getclass (). getname (), E. getmessage ();} finally {}}}
C code:
// Client # include <sys/types. h> # include <sys/socket. h> # include <sys/UN. h> # include <unistd. h> # include <stdlib. h> # include <stdio. h> # include <Android/log. h> # define this_file "ipc_client.c" int send_remote_request (char * MSG, int size) {int result; int Len; int namelen; int localsocket; struct sockaddr_un remote; char * name = "com. example. mysoftphone. localsocket "; // same as the upper layer of Java, localsocket = socket (af_unix, so Ck_stream, 0); If (localsocket =-1) {__ android_log_print (android_log_error, this_file, "socket failed! "); Return-1;} remote. sun_family = af_unix; remote. sun_path [0] = '\ 0';/* abstract namespace */strcpy (remote. sun_path + 1, name); namelen = strlen (name); Len = 1 + namelen + offsetof (struct sockaddr_un, sun_path); Result = connect (localsocket, (struct sockaddr *) & remote, Len); If (result =-1) {__ android_log_print (android_log_error, this_file, "Connect failed! "); Return-1;} result = Send (localsocket, MSG, size, 0); If (result =-1) {__ android_log_print (android_log_error, this_file, "Send failed! "); Return-1;} Close (localsocket); Return 0 ;}