Server  -  JAVA

package com.jim.ndkdemo;

import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; class ServerSocketThread extends Thread
{
public static String TAG = "zjm";
private boolean keepRunning = true;
private LocalServerSocket serverSocket; private void readMsg(LocalSocket interactClientSocket) {
StringBuilder recvStrBuilder = new StringBuilder();
InputStream inputStream = null;
try
{
inputStream = interactClientSocket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
char[] buf = new char[4096];
int readBytes = -1;
while ((readBytes = inputStreamReader.read(buf)) != -1) {
String tempStr = new String(buf, 0, readBytes);
recvStrBuilder.append(tempStr);
}
Log.d(TAG, "Receive MSG: " + recvStrBuilder.toString());
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "resolve data error !");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} @Override
public void run()
{
try {
serverSocket = new LocalServerSocket("pym_local_socket");
} catch (IOException e) {
e.printStackTrace();
keepRunning = false;
}
while(keepRunning)
{
Log.d(TAG, "wait for new client coming !");
try {
LocalSocket interactClientSocket = serverSocket.accept();
//由于accept()在阻塞时,可能Activity已经finish掉了,所以再次检查keepRunning
if (keepRunning) {
Log.d(TAG, "new client coming !");
readMsg(interactClientSocket);
}
} catch (IOException e) {
e.printStackTrace();
keepRunning = false;
}
} if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} public class MainActivity extends AppCompatActivity { public static String TAG = "zjm";
private ServerSocketThread socketThread;
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); socketThread = new ServerSocketThread();
socketThread.setName("zjmserver");
socketThread.start(); try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} // Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText(stringFromJNI()); } /**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}

Client - C++

#include <jni.h>
#include <string>
#include <android/log.h> #include <sys/socket.h>
#include <sys/un.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h> #define ANDROID_SOCKET_NAMESPACE_ABSTRACT 0 #define NO_ERR 0
#define CREATE_ERR -1
#define CONNECT_ERR -2
#define LINUX_MAKE_ADDRUN_ERROR -3
#define CLOSE_ERR -5 #define LOG_TAG "zjm"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) /* 构造sockaddr_un */
int socket_make_sockaddr_un(const char *name, int namespaceId, struct sockaddr_un *p_addr, socklen_t *socklen)
{
size_t namelen; memset(p_addr, 0x00, sizeof(*p_addr));
namelen = strlen(name); // Test with length +1 for the *initial* '\0'.
if ((namelen + ) > sizeof(p_addr->sun_path)) {
return LINUX_MAKE_ADDRUN_ERROR;
}
p_addr->sun_path[] = ;
memcpy(p_addr->sun_path + , name, namelen); p_addr->sun_family = AF_LOCAL;
*socklen = namelen + offsetof(struct sockaddr_un, sun_path) + ; return NO_ERR;
} /* 连接到相应的fileDescriptor上 */
int socket_local_client_connect(int fd, const char *name, int namespaceId, int type)
{
struct sockaddr_un addr;
socklen_t socklen;
//size_t namelen;
int ret;
ret = socket_make_sockaddr_un(name, namespaceId, &addr, &socklen);
if (ret < ) {
return ret;
} if(connect(fd, (struct sockaddr *) &addr, socklen) < ) {
return CONNECT_ERR;
} return fd;
} /* 创建本地socket客户端 */
int socket_local_client(const char *name, int namespaceId, int type)
{
int socketID;
int ret; socketID = socket(AF_LOCAL, type, );
if(socketID < ) {
return CREATE_ERR;
} ret = socket_local_client_connect(socketID, name, namespaceId, type);
if (ret < ) {
close(socketID);
return ret;
} return socketID;
} int SendMsgBySocket() {
int socketID;
struct sockaddr_un serverAddr;
char path[] = "pym_local_socket\0";
int ret; socketID = socket_local_client(path, ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
if (socketID < ) {
return socketID;
}
//Send Msg
char buf[] = "hello";
ret = write(socketID, buf, strlen(buf)); ret = close(socketID);
if (ret < ) {
return CLOSE_ERR;
} return NO_ERR;
} extern "C"
JNIEXPORT jstring JNICALL
Java_com_jim_ndkdemo_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++"; int pid = fork();
if (pid == ) {
//sub process
setpgid(, );
int ret = SendMsgBySocket();
LOGI("ret = %d", ret);
} else if (pid > ) {
//int ret = SendMsgBySocket();
//LOGI("ret = %d", ret);
} else {
LOGI("pid < 0");
} sleep(); return env->NewStringUTF(hello.c_str());
}

socket in android的更多相关文章

  1. Socket for android 简单实例

    最近在实现socket通信,所以写个demo来简单实现下.我用了一种是原始的socket实现,另一种是MINA框架来实现的. 下载demo:http://download.csdn.net/detai ...

  2. 非堵塞socket实现android手机与PC的文件传输

    项目须要是通过WIFI建立手机和PC的通信,然后自己定义一个简单的协议对要传输的文件进行校验,传输的文件是2张3M的图片,要求考虑网络中断情况处理. 我这里採用的是非堵塞socket来实现的,之前查过 ...

  3. 基于Socket的Android手机视频实时传输

    首先,简单介绍一下原理.主要是在手机客户端 (Android)通过实现Camera.PreviewCallback接口,在其onPreviewFrame重载函数里面获取摄像头当前图像数据, 然后通过S ...

  4. android socket 线程连接openwrt与arduino单片机串口双向通信

    package zcd.netanything; import java.io.BufferedReader; import java.io.InputStreamReader; import jav ...

  5. Socket实现粗略的Android聊天功能

    面试时写过,但是很乱,今天看到代码库里有一个,还是很规范的,贴出来. 主要用到俩类,一个是ServerSocket.class 一个是Socket.class. 记得要加权限:  <uses-p ...

  6. Android进程间通信之socket通信

    用Java中的socket编程. 通过socket实现两个应用之间的通信,可以接收和发送数据,同时将接收到的数据显示在activity界面上. Server端: ServerLastly.java p ...

  7. 一个Android Socket的例子

    1.开篇简介 Socket本质上就是Java封装了传输层上的TCP协议(注:UDP用的是DatagramSocket类).要实现Socket的传输,需要构建客户端和服务器端.另外,传输的数据可以是字符 ...

  8. Android网络编程之Socket

    Socket(套接字)是一种通信机制,可以实现单机或跨网络进行通信,其创建需要明确的区分C(客户端)/S(服务器端),支持多个客户端连接到同一个服务器.有两种传输模式: 1).面向连接的传输:基于TC ...

  9. Android Socket通信

    1.TCP: xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: ...

随机推荐

  1. 嘴巴题4 「BZOJ1827」[Usaco2010 Mar] gather 奶牛大集会

    1827: [Usaco2010 Mar]gather 奶牛大集会 Description Bessie正在计划一年一度的奶牛大集会,来自全国各地的奶牛将来参加这一次集会.当然,她会选择最方便的地点来 ...

  2. 初学C#的简单编程题合集(更新)

    一 编写一个控制台应用程序,要求完成下列功能. 1)   接收一个整数 n. 2)   如果接收的值 n 为正数,输出 1 到 n 间的全部整数. 3)   如果接收的值为负值,用 break 或者 ...

  3. Redis Replication & Sentinel

    实践目标: Redis Replication 一主:192.168.1.104 双从:192.168.1.101 192.168.1.103 Sentinel:192.168.1.102 系统环境: ...

  4. What is python .. (“dot dot”) notation syntax?

    What you have is a float literal without the trailing zero, which you then access the __truediv__met ...

  5. pin, port, cell, net

    一幅图即可解释清楚: 更标准的官方解释:

  6. agc034

    A:题意:你有一个1 * n的网格,有些地方是障碍.你有两个人,分别要从a到b和从c到d,一次只能向右跳1步或者两步.求是否可行. 解:先判断有没有2个连续的障碍,然后判断是否能错车. #includ ...

  7. 开方运算的DSP实现

    //=============================================== //函数名:VSqrt3 //功能:  实现对32位定点数的开方 //性能:  60M主频28015 ...

  8. 自定义切面实现用户日志记录--AOP

    在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是OOP的延续,是软件开发中的 ...

  9. Django项目:CRM(客户关系管理系统)--36--28PerfectCRM实现King_admin编辑限制

    #admin.py # ————————01PerfectCRM基本配置ADMIN———————— from django.contrib import admin # Register your m ...

  10. Django项目:CRM(客户关系管理系统)--22--14PerfectCRM实现King_admin分页的省略显示

    {#table_data_list.html#} {## ————————08PerfectCRM实现King_admin显示注册表的字段表头————————#} {% extends 'king_m ...