views:

24

answers:

1

Hello. I need to pass a native winsock socket created by C++ application to a library in my application that uses java.net.Socket to connect to a server. This winsock appication already take care of connecting the socket. how can I explicitly set the socket descriptor of java.net.Socket?

A: 

I encountered such a problem on Unix, not sure if the same mechanism works for you with WinSock.

In our case, a program in C creates a socket using special hardware. The C program spawns the Java program passes it the socket. The Java program then constructs input/output stream from the file descriptor of the socket so it can read/write to it just like a normal socket.

The Java code snippet is here,

    Class<FileDescriptor> clazz = FileDescriptor.class;

    Constructor<FileDescriptor> c;
    try {
            c = clazz.getDeclaredConstructor(new Class[] { Integer.TYPE });
    } catch (SecurityException e) {
            e.printStackTrace();
            return;
    } catch (NoSuchMethodException e) {
            e.printStackTrace();
            return;
    }

    c.setAccessible(true);
    FileDescriptor fd;
    try {
            fd = c.newInstance(new Integer(socket));
    } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return;
    } catch (InstantiationException e) {
            e.printStackTrace();
            return;
    } catch (IllegalAccessException e) {
            e.printStackTrace();
            return;
    } catch (InvocationTargetException e) {
            e.printStackTrace();
            return;
    }

    FileOutputStream os = new FileOutputStream(fd);
    FileInputStream is = new FileInputStream(fd);
ZZ Coder
Thats nice, I just need one more step forward since I must provide a java socket and not input/output streams.
erb