【发布时间】:2015-01-09 06:47:01
【问题描述】:
我在尝试将 BSD 客户端套接字连接到服务器时遇到了一些问题。 套接字创建和连接是用 JNI 实现的。实际的连接是通过java代码建立的。
JNI 部分:
#include <jni.h>
#include <unistd.h>
#include <string.h>
#include <sys/endian.h>
#include <sys/ioctl.h>
#include <sys/errno.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <netinet/in.h>
JNIEXPORT jint JNICALL Java_com_example_socketclinet_Native_socket
(JNIEnv *, jclass, jint, jint, jint);
JNIEXPORT jint JNICALL Java_com_example_socketclinet_Native_connect
(JNIEnv *, jclass, jint, jint, jint);
jint JNICALL Java_com_example_socketclinet_Native_socket
(JNIEnv *env, jclass cls, jint domain, jint type, jint protocol)
{
return socket(domain, type, protocol);
}
jint JNICALL Java_com_example_socketclinet_Native_connect
(JNIEnv *env, jclass cls, jint socket, jint address, jint port)
{
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(address);
addr.sin_port = htons(port);
return connect(socket, (const struct sockaddr *)&addr, sizeof(struct sockaddr_in));
}
Java 原生桥接类:
class Native
{
static
{
System.loadLibrary("mylib");
}
public static final int SOCK_STREAM = 2;
public static final int AF_INET = 2;
public static native int socket(int domain, int type, int protocol);
public static native int connect(int socket, int address, int port);
}
原生类用法:
int socket = Native.socket(Native.AF_INET, Native.SOCK_STREAM, 0);
if (socket < 0)
{
System.err.println("Socket error: " + socket);
return;
}
byte[] address = { .... }; // 192.168.xxx.xxx
int addr = address[0] << 24 | address[1] << 16 | address[2] << 8 | address[3];
int port = ....;
int result = Native.connect(socket, addr, port);
if (result < 0)
{
System.err.println("Connection failed: " + result);
}
else
{
System.out.println("Connected");
}
即使没有服务器在运行(在设备和模拟器上),“connect”方法也总是返回“0”。
• 我在清单文件中设置了“INTERNET”权限(没有它,“socket”函数返回 -1)
• 相同的代码在 iOS 和 Mac OS 上运行良好。
• 测试环境:Nexus 5 (4.4.4), android-ndk-r10d
任何帮助将不胜感激!
【问题讨论】:
标签: java android sockets android-ndk java-native-interface