(已完成)java socket-客户端套接字连接过程 源码分析.md

1,375 阅读1分钟

应用程序

Socket客户端套接字.连接方法()

www.runoob.com/java/net-se… demo

java net包-socket

1.SocketImpl1

class SocksSocketImpl extends PlainSocketImpl implements SocksConsts {

 


2.SocketImpl2

/*
 * This class PlainSocketImpl simply delegates to the appropriate real
 * SocketImpl. We do this because PlainSocketImpl is already extended
 * by SocksSocketImpl.
 * <p>
 * There are two possibilities for the real SocketImpl,
 * TwoStacksPlainSocketImpl or DualStackPlainSocketImpl. We use
 * DualStackPlainSocketImpl on systems that have a dual stack
 * TCP implementation. Otherwise we create an instance of
 * TwoStacksPlainSocketImpl and delegate to it.
 *
 * @author Chris Hegarty
 */
class PlainSocketImpl extends AbstractPlainSocketImpl

{


 /**

     * Constructs an empty instance.

     */

    PlainSocketImpl() {

        if (useDualStackImpl) {

            impl = new DualStackPlainSocketImpl(exclusiveBind);

        } else {

            impl = new TwoStacksPlainSocketImpl(exclusiveBind);

        }

    }


//https://github.com/frohoff/jdk8u-dev-jdk/blob/master/src/windows/classes/java/net/DualStackPlainSocketImpl.java

void socketConnect(InetAddress address, int port, int timeout)
        throws IOException {
        int nativefd = checkAndReturnNativeFD();

        if (address == null)
            throw new NullPointerException("inet address argument is null.");

        int connectResult;
        if (timeout <= 0) {
            connectResult = connect0(nativefd, address, port);
        } else {
            configureBlocking(nativefd, false);
            try {
                connectResult = connect0(nativefd, address, port);
                if (connectResult == WOULDBLOCK) {
                    waitForConnect(nativefd, timeout);
                }
            } finally {
                configureBlocking(nativefd, true);
            }
        }
        /*
         * We need to set the local port field. If bind was called
         * previous to the connect (by the client) then localport field
         * will already be set.
         */
        if (localport == 0)
            localport = localPort0(nativefd);
    }
static native int connect0(int fd, InetAddress remote, int remotePort)
throws IOException; //最终的话 都是调用 操作系统的套接字连接,具体流程是:jdk socket——》jvm native——》操作系统

总结

1.关于包
socket所有的类都在java.net包。

nio类都在jdk nio包。

2.流程
最终的话 都是调用 操作系统的套接字连接,具体流程是:jdk socket——》jvm native——》操作系统