首页 > 代码库 > android的NDK和java进行本地socket通信
android的NDK和java进行本地socket通信
关于Android应用与Framework的socket通信,相信关心这个问题的朋友们已经看过《android使用socket使底层和framework通信》这篇文章,美中不足的是作者只贴出一些关键的代码片段而并没有放出源码。我这里还是以一个能实际运行的例子为基础来讲,这样也方便大家学习。
首先看一下效果,如下图。我填写姓名"Potter",选择性别"Mr"然后点击发送,底层socket收到消息后将消息直接返回给我,我将返回的结果(Mr.Potter)直接显示在Result。
编写socket服务端代码,生成可执行脚本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]; //这一步很关键,就是获取init.rc中配置的名为 "htfsk" 的socket fdListen = android_get_control_socket(SOCKET_NAME); if (fdListen < 0) { sprintf(log,"Failed to get socket ‘" SOCKET_NAME "‘ errno:%d", errno); __android_log_write(ANDROID_LOG_DEBUG,"FTM_JNI",log); exit(-1); } //开始监听 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); } //等待Socket客户端发启连接请求 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); } while(1){ //循环等待Socket客户端发来消息 __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; } //发送消息回执给Socket客户端 if(send(new_fd,buff,strlen(buff),0)==-1) { perror("send"); close(new_fd); exit(0); } } close(new_fd); close(fdListen); return 0; }
3、编写客户端java代码。核心代码如下:
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客户端 * * @author lai_zs * @date:2012-3-17 下午12:15:09 */ public class SocketClient { private final String SOCKET_NAME = "htfsk"; private 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(); } /** * 发送消息 * @param msg * @return 返回Socket服务端的消息回执 */ 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"; } /** * 异步连接Socket,如果连接不上会尝试重复连接十次 * * @author Administrator * */ private class ConnectSocketThread extends Thread { @Override public void run() { while (!isConnected && connetTime <= 10) { 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"); } } } } /** * 关闭Socket */ public void closeSocket() { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } }
<iframe id="google_ads_frame2" vspace="0" height="250" marginHeight="0" src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3447371224873639&output=html&h=250&slotname=8660799060&adk=1970350646&w=300&lmt=1398844505&flash=11.9.900.117&url=http%3A%2F%2Fwww.cnblogs.com%2Fxiaochao1234%2Fp%2F3699663.html&dt=1398844482661&shv=r20140424&cbv=r20140417&saldr=sb&prev_slotnames=4356862740&correlator=1398844482468&frm=20&ga_vid=429972749.1397695120&ga_sid=1398816550&ga_hid=1078599136&ga_fc=1&u_tz=480&u_his=162&u_java=1&u_h=768&u_w=1364&u_ah=740&u_aw=1364&u_cd=16&u_nplug=0&u_nmime=0&dff=verdana&dfs=16&adx=0&ady=4367&biw=314&bih=74&eid=317150304&oid=3&rx=0&eae=0&docm=9&vis=0&fu=0&ifi=2&xpc=gSSR6P7REU&p=http%3A//www.cnblogs.com&dtd=41" frameBorder="0" width="300" allowTransparency="true" name="google_ads_frame2" marginWidth="0" scrolling="no" hspace="0"></iframe><iframe id="google_ads_frame3" vspace="0" height="250" marginHeight="0" src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3447371224873639&output=html&h=250&slotname=8660799060&adk=1970350646&w=300&lmt=1398844505&flash=11.9.900.117&url=http%3A%2F%2Fwww.cnblogs.com%2Fxiaochao1234%2Fp%2F3699663.html&dt=1398844482708&shv=r20140424&cbv=r20140417&saldr=sb&prev_slotnames=4356862740%2C8660799060&correlator=1398844482468&frm=20&ga_vid=429972749.1397695120&ga_sid=1398816550&ga_hid=1078599136&ga_fc=1&u_tz=480&u_his=162&u_java=1&u_h=768&u_w=1364&u_ah=740&u_aw=1364&u_cd=16&u_nplug=0&u_nmime=0&dff=verdana&dfs=16&adx=306&ady=4617&biw=314&bih=74&eid=317150304&oid=3&rx=0&eae=0&docm=9&vis=0&fu=0&ifi=3&xpc=fri4kxYDiN&p=http%3A//www.cnblogs.com&dtd=41" frameBorder="0" width="300" allowTransparency="true" name="google_ads_frame3" marginWidth="0" scrolling="no" hspace="0"></iframe>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。