Http://blog.chinaunix.net/uid-20364597-id-3794822.html
For example, we run Android on the hardware, but we need another program to handle some things (this program also runs on the same machine ). To put it simply, two independent processes communicate with each other, and the socket is the best. Generally, in a Linux environment, if two independent C Programs communicate with each other, one server and the other client can create a socket file node in the/tmp directory to communicate with each other. For example, the client can write as follows:
# Define socket_path "/tmp/mysocket"
Struct sockaddr_un address;
Int Len, result;
Int server_fd;
Server_fd = socket (af_unix, sock_stream, 0 );
Address. sun_family = af_unix;
Strcpy (address. sun_path,Socket_path);
Len = sizeof (Address );
Result = connect (server_fd, (struct sockaddr *) & Address, Len );
If (result =-1 ){
Printf ("Connect fail \ n ");
Close (server_fd );
Server_fd = 0;
Return-1;
}
This is the communication method between two C Programs, but what should I do in Android? How can I implement the server through Java on Android and the client on another C program? Some people may think of sending messages to the native layer on the android end, and then sending messages to the native layer. In this way, the communication between two C Programs is changed, however, the communication between Java and native has to be implemented by itself. Isn't that very troublesome.
Okay. Let's take a look at the localserversocket class of Android. This class will create a local socket, but this socket is not shown in the file system as below in C:
Ss = new localserversocket ("My. socket ");
After the server is created, the socket node name is also known. But how can I connect to the C end? If the node file cannot be found in the C program, the call to connect will certainly fail, what should I do here? Let's look at the code (note the red part ):
# Define socket_path "/tmp/mysocket"
Int sockfd =-1;
Int addrlen = 0;
Struct sockaddr_un ADDR;
Sockfd = socket (pf_unix, sock_stream, 0 );
If (sockfd <0 ){
Fprintf (stderr, "can not create socket for twin! \ N ");
Return-1;
}
Bzero (& ADDR, sizeof (ADDR ));
Strcpy (& ADDR. sun_path [1], socket_path );
ADDR. sun_family = af_unix;
Addrlen = 1 + strlen (socket_path) + sizeof (ADDR. sun_family );
If (connect (sockfd, (struct sockaddr *) & ADDR, addrlen) <0 ){
Fprintf (stderr, "can not connect server! \ N ");
Close (sockfd );
Return-1;
}
To communicate with the socket created by the localserversocket class of Android, you only need to add '\ x00' before the socket node name, the reason is that the underlying code of the localserversocket class creates a socket in this way, so the client must connect like this, otherwise the system will think it is a different socket. this is the abstract namespace in Android.