java服务端程序放到public void onCreate(Bundle savedInstanceState) {里面
//======================localsocket通信机制======================================================
// 接收线程
Thread local_receive2 = new Thread(){
@Override
public void run() {
try {
LocalServerSocket server2 = new LocalServerSocket("crl.localsocket");
//定义的名字crl.localsocket,对应native层
LocalSocket receiver2 = null;
InputStream in = null;
DataInputStream din = null;
boolean ruing =true;
while (ruing) {
receiver2 = server2.accept();
in = receiver2.getInputStream(); //获取输入流,并创建相应的数据输入流
din = new DataInputStream(in);
if (receiver2 != null) {
String s1 = din.readLine(); //读入传来的字符串
Log.i("socket", "s1 ="+s1);
// threadin(s1,2);
}
}
din.close();
in.close();
receiver2.close();
server2.close();
} catch (IOException e) {
}
}
};
local_receive2.start();
c++程序客服端
#include <stdio.h>
#include <string.h>
#include<stdarg.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
void send_remote_request(char *msg)
{
int localsocket, len;
struct sockaddr_un remote;
if ((localsocket = socket(AF_UNIX,SOCK_STREAM, 0)) == -1) {
printf("fail 1\n");
exit(1);
}
char *name="crl.localsocket";//与java层相同
remote.sun_path[0] = '\0';
strcpy(remote.sun_path+1, name);
remote.sun_family = AF_UNIX;
int nameLen = strlen(name);
len = 1 + nameLen + offsetof(struct sockaddr_un, sun_path);
if (connect(localsocket, (struct sockaddr *)&remote, len) == -1) {
printf("fail 2\n");
return;
}
if (send(localsocket, msg,strlen(msg),0) == -1) {
printf("fail 3\n");
return;
}
close(localsocket);
}
int main ()
{
char * str1="add_by_crl_for_test_socket";
while(1){
send_remote_request(str1);
usleep(100*1000);
}
return 0;
}