一、前言
关于基于edtftpj的源码包中的com.enterprisedt.net.ftp.internal.SocketUtils套接字工具栏,对根据InetAddress端口创建套接字Socket连接、判断其是否连接正常等操作。
二、源码说明
package com.enterprisedt.net.ftp.internal;@b@@b@import com.enterprisedt.util.debug.Logger;@b@import java.io.IOException;@b@import java.lang.reflect.Constructor;@b@import java.lang.reflect.InvocationTargetException;@b@import java.lang.reflect.Method;@b@import java.net.InetAddress;@b@import java.net.Socket;@b@@b@public class SocketUtils@b@{@b@ private static Logger log = Logger.getLogger("SocketUtils");@b@ private static boolean timeoutSupported = true;@b@ private static boolean isConnectedSupported = true;@b@@b@ public static Socket createSocket(InetAddress host, int port, int timeout)@b@ throws IOException@b@ {@b@ if ((timeout == 0) || (!(timeoutSupported))) {@b@ return new Socket(host, port);@b@ }@b@@b@ try@b@ {@b@ Class socketAddress = Class.forName("java.net.SocketAddress");@b@ Method connectMethod = class$java$net$Socket.getMethod("connect", new Class[] { socketAddress, Integer.TYPE });@b@@b@ Socket sock = (Socket)Socket.class.newInstance();@b@@b@ Class inetSocketAddress = Class.forName("java.net.InetSocketAddress");@b@ Constructor inetSocketAddressCtr = inetSocketAddress.getConstructor(new Class[] { InetAddress.class, Integer.TYPE });@b@@b@ Object address = inetSocketAddressCtr.newInstance(new Object[] { host, new Integer(port) });@b@@b@ log.debug("Invoking connect with timeout=" + timeout);@b@ connectMethod.invoke(sock, new Object[] { address, new Integer(timeout) });@b@ log.debug("Connected successfully");@b@ return sock;@b@ }@b@ catch (InvocationTargetException ex) {@b@ Throwable target = ex.getTargetException();@b@ if (target instanceof IOException)@b@ throw ((IOException)target);@b@ log.debug("Could not use timeout connecting to host (" + ex.toString() + ")");@b@ timeoutSupported = false;@b@ return new Socket(host, port);@b@ }@b@ catch (Exception ex) {@b@ log.debug("Could not use timeout connecting to host (" + ex.toString() + ")");@b@ timeoutSupported = false; }@b@ return new Socket(host, port);@b@ }@b@@b@ public static boolean isConnected(Socket sock)@b@ throws IOException@b@ {@b@ if (!(isConnectedSupported))@b@ return true;@b@ try@b@ {@b@ Method connectedMethod = Socket.class.getMethod("isConnected", (Class[])null);@b@@b@ Boolean result = (Boolean)connectedMethod.invoke(sock, (Object[])null);@b@ return result.booleanValue();@b@ }@b@ catch (InvocationTargetException ex) {@b@ Throwable target = ex.getTargetException();@b@ if (target instanceof IOException)@b@ throw ((IOException)target);@b@ isConnectedSupported = false;@b@ log.debug("Could not use Socket.isConnected (" + ex.toString() + ")");@b@ return true;@b@ }@b@ catch (Exception ex) {@b@ log.debug("Could not use Socket.isConnected (" + ex.toString() + ")");@b@ isConnectedSupported = false; }@b@ return true;@b@ }@b@}