Can I get a Java Socket from a file descriptor number?

和自甴很熟 提交于 2019-12-02 10:19:38

You can't do this legally. However, you can do a hack like this (Don't try this at home). You can read from is and write to os.

    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);

What would you want a Socket for? The only useful methods in a socket are getInputStream and getOutputStream but if you’re running as a CGI you already have those: they’re called System.in and System.out. :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!