In fact, this title is meaningless. But I want to write it here if I want to check a lot of information.
The socket programming of Android-JNI is to call socket programming of underlying Linux. The Android platform generally only needs to care about the client code, as shown below: (copy from the far-sighted embedded Linux application development materials, there is no good example at hand)
/* Client. C */# include <stdio. h> # include <stdlib. h> # include <errno. h> # include <string. h> # include <netdb. h> # include <sys/types. h> # include <netinet/in. h> # include <sys/socket. h> # define servport 8591 # define maxdatasize 100 Main (INT argc, char * argv []) {int sockfd, sendbytes; char Buf [maxdatasize]; struct hostent * Host; struct sockaddr_in serv_addr; If (argc <2) {fprintf (stderr, "Please enter the server's H Ostname! \ N "); exit (1);}/* address resolution function */If (host = gethostbyname (argv [1]) = NULL) {perror ("gethostbyname"); exit (1);} printf ("% s", host-> h_name ); /* Create socket */If (sockfd = socket (af_inet, sock_stream, 0) =-1) {perror ("socket"); exit (1 );} /* set the parameter */serv_addr.sin_family = af_inet in the sockaddr_in struct; serv_addr.sin_port = htons (servport); struct = * (struct in_addr *) Host-> h_addr ); bzero (& (serv_addr.sin_zero), 8);/* call the connect function to initiate a connection to the server */If (connect (sockfd, (struct sockaddr *) & serv_addr, \ sizeof (struct sockaddr) =-1) {perror ("Connect"); exit (1 );} /* send the message to the server */If (sendbytes = Send (sockfd, "hello", 5, 0) =-1) {perror ("send "); exit (1);} Close (sockfd );}
Then, you can change the sample of Android-ndk to JNI.
The following method can be used to receive messages: (refer to apue)
long ReceiveMessage(BYTE *buf,UINT bufSize,UINT *recvbufLen,UINT nTimeOut){LOGI("ReceiveMessage");long lRet = -1;int recvbytes;uint startTime = GetTickCount(),endTime;do{endTime = GetTickCount();if ((recvbytes=recv(sockfd, buf, bufSize, MSG_DONTWAIT)) == -1){lRet = -1;//LOGI("recv error");//LOGII(errno,"recv errno",__LINE__); // 11 : Resource temporarily unavailable}else{lRet = 0;break;}}while(lRet == -1 && endTime - startTime < nTimeOut);*recvbufLen = recvbytes;if(recvbytes > 0)LOGArr((unsigned char*)buf,recvbytes);return lRet;}
In the above example, the output parameter is passed through the pointer rather than referenced because JNI is compiled in the. c file and the C ++ feature is not supported. The JNI-C ++ section is not completely clear yet, so I will write another article later.
The most important thing to note is that androidmanifest. xml under the project directory must be added with network permission support before it can be called:
<! -- Added support for JNI socket --> <uses-Permission Android: Name = "android. Permission. Internet"/>