Android Socket学习java与native_socket通信

Posted we1less

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Socket学习java与native_socket通信相关的知识,希望对你有一定的参考价值。

native端   socket_sevice.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/epoll.h>
#include <sys/un.h>
int main()
{
    char *socket_path = "server-socket";
    struct sockaddr_un serun, cliun;
    socklen_t cliun_len;
    int listenfd, connfd, size;
    char buf[80];
    int i, n;
    if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
        perror("socket error");
        exit(1);
    }
    //unlink(socket_path);
    memset(&serun, 0, sizeof(serun));
    serun.sun_family = AF_UNIX;
    serun.sun_path[0] = 0; //这个写法是虚拟地址
    strcpy(serun.sun_path+1,socket_path);
    socklen_t addrlen_ = sizeof(serun.sun_family) + strlen(socket_path) + 1;
    int ret = bind(listenfd, (struct sockaddr*)&serun,addrlen_);
    if(ret == -1)
    {
        perror("bind");
        exit(0);
    }
    // 3. 监听
    ret = listen(listenfd, 20); //最多20个用户
    if(ret == -1)
    {
        perror("listen");
        exit(0);
    }

   
    while(1)
    {
	printf("wait connect...\\n");
	socklen_t l =   sizeof(struct sockaddr_un);
        int connfd = accept(listenfd, (struct sockaddr *)&cliun, &l);
        if(connfd == -1)
        {
            perror("accept");
            exit(-1);
        }
        printf("a new client connected! ");
    
        int count = read(connfd, buf, sizeof(buf));
        if(count == 0)//客户端关闭了连接
        {
            printf("客户端关闭了连接。。。。\\n");
          
        }
        else
        {
            if(count == -1)
            {
                perror("read");
                exit(-1);
            }
            else
            {
                //正常通信
                printf("client say: %s\\n" ,buf);
		write(connfd,"received ok",sizeof("received ok"));
            }
        }
    }
    close(listenfd);
    return 0;
}

mk

LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

LOCAL_SRC_FILES:= \\
    socket_service.c \\

LOCAL_CFLAGS += -Wall -Wextra

LOCAL_MODULE:= socket_service

include $(BUILD_EXECUTABLE)

apk

package com.godv.godvsocket;

import androidx.appcompat.app.AppCompatActivity;

import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {

    LocalSocket lsocket;
    BufferedWriter br;
    EditText sendCmdText;
    TextView receiveText;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendCmdText = findViewById(R.id.sendCmdText);
        receiveText = findViewById(R.id.receiveText);
        button = findViewById(R.id.send);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });
    }


    private void sendMessage() {
        try {
            lsocket = new LocalSocket();
            LocalSocketAddress address = new LocalSocketAddress("server-socket",
                    LocalSocketAddress.Namespace.ABSTRACT);
            lsocket.connect(address);
            String result;
            Log.i("godv", "rootclient send cmd to rootServer cmd = " +
                    sendCmdText.getText().toString());
            br = new BufferedWriter(new OutputStreamWriter(lsocket.getOutputStream()));
            br.write(sendCmdText.getText().toString());
            br.newLine();
            br.flush();
//            br.close();

            Log.d("test", "========发送成功========");
            InputStream inputStream = lsocket.getInputStream();
            BufferedReader buffer = null;
            buffer = new BufferedReader(new InputStreamReader(inputStream));
            String tmpStr = null;
            while (inputStream.available() == 0) {
                try {
                    //    Log.d("lsm", "========sleep======== inputStream.available() = " +inputStream.available());
                    Thread.sleep(1);
                } catch (Exception e) {

                }
            }
            byte[] buf = new byte[inputStream.available() - 1];
            inputStream.read(buf, 0, inputStream.available() - 1);
            String str = new String(buf);
            Log.d("godv", "========接受成功======== inputStream.available() = " +
                    inputStream.available() + "read str  = " + str);
            final String str1 = str;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    receiveText.setText(str1);
                }
            });

            buffer.close();

            lsocket.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("godv", "rootclient rootServer 发送失败", e);
        }
    }

}

可以自行改造一下

以上是关于Android Socket学习java与native_socket通信的主要内容,如果未能解决你的问题,请参考以下文章

Android Framework实战开发-socket跨进程通信之native程序与apk java通信

Android Framework实战开发-socket跨进程通信之native程序与apk java通信

20182332 实验四《Java Socket编程 》实验报告

android 中的 GCM 与 Socket

Android SystemProperties系统属性详解

Android 客户端Socket 与 Java服务端ServerSocket 简单小例子