在Android系统使用socket在Java层和native之间数据通信

Android是基于Linux的系统,系统底层机制基本上是相同的,因为分本地代码和java代码,并且是java代码通过jni调用本地代码执行。

因为UDP报文发送是有局限的,局限就是当发送方的速度远远的超过接受方的时候,底层会大量的丢失数据,而且用UDP还会比较容易引起端口的阻塞,因此需要更加强大的类来实现类似的功能。LocalServerSocket和LocalSocket正是在这样的情况下产生的,是以UNIX空间为缓冲区来进行数据的存储的.

实例一:Native本地代码作客户端发送请求,Java端作服务器端创建socket,并监听处理socket请求:

import android.net.LocalServerSocket;
import android.net.LocalSocket;


class SocketListener extends Thread {

@Override
        public void run() {
            try {
                LocalServerSocket server = new LocalServerSocket("com.jenny.vnc.localsocket");
                while (true) {   
                    LocalSocket receiver = server.accept();
                    if (receiver != null) {
                        InputStream input = receiver.getInputStream();
                        int readed = input.read();
                                                           
                        ...........//handle   
                       
                    }

}

server.close();


            } catch (IOException e) {
                Log.e(getClass().getName(), e.getMessage());
            }
        }
    }
JNI 的Native端代码做客户端:
#include <sys/socket.h>
void send_remote_request(char *msg)
{
    int localsocket, len;
    struct sockaddr_un remote;

if ((localsocket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
    exit(1);
    }

char *name="com.jenny.vnc.localsocket";//与java上层相同哦

remote.sun_path[0] = '\0';  /* abstract namespace */
    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) {
    return;
    }
   
    if (send(localsocket, msg, strlen(msg),0) == -1) {
    return;
    }
   
    close(localsocket);
}


实例二、Java作客户端发送请求,Native本地代码作服务器端监听处理socket请求:

Java层的主要代码:

1. LocalSocket so = null;
   2. LocalSocketAddress addr;
   3. so = new LocalSocket();
   4. addr = new LocalSocketAddress(SOCKET_NAME, LocalSocketAddress.Namespace.RESERVED);
   5. so.connect(addr);

如果能正常connect到addr,那就可以像一般文件操作那样进行io读写了。

native层的主要代码:

1. cli_fd = android_get_control_socket(SOCKET_NAME);
   2. retval = listen(cli_fd, backlog);
   3. cli_fd_cmd = accept(cli_fd, (sockaddr *)&peeraddr, &socklen);

如果能够正常accept到java端的连接,那就可以用标准的io读写操作来读写数据了。

linux

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyszgs.html