1
BSD 클라이언트 소켓을 서버에 연결하는 동안 몇 가지 문제가 발생합니다. 소켓 생성 및 연결은 JNI로 구현됩니다. 실제 연결은 Java 코드를 통해 설정됩니다.Android BSD 소켓 연결
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));
}
자바 네이티브 브리지 클래스 :
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");
}
은 "연결"방법은 항상 경우에도 "0"를 반환 실행중인 서버가 없습니다 (장치 및 시뮬레이터 모두).
• 매니페스트 파일에 "인터넷"권한이 설정되어 있습니다 ("소켓"함수가 -1을 반환하지 않음)
• 동일한 코드가 iOS 및 Mac OS에서 완벽하게 작동합니다.
• 테스트 환경 : Nexus 5 (4.4.4), android-ndk-r10d
모든 도움을 주실 수 있습니다!
브로드 캐스트 주소에 TCP 소켓을 연결할 수 없습니다. – EJP
@Digit, 작동하지 않았습니다. 또한 네이티브 코드의 주소를 하드 코드하려고했습니다. 나는 자바에서 소켓 통신 코드를 작성하고 JNI 바인딩 (매력처럼 작동)을 추가했다. –