什么是Socket?
API说:他是套接字,两台机器连接的端点。他的实际工作由SocketIml执行。
没图说个**,下面用个图能说明Socket,在哪个位置:
相关源码:
1.Socket:
属性:SocketImpl impl,socket的实现,就是API说的,实际工作由它执行。
public
class Socket implementsjava.io.Closeable {/*** Various states of this socket.*/
private boolean created = false;private boolean bound = false;private boolean connected = false;private boolean closed = false;private Object closeLock = newObject();private boolean shutIn = false;private boolean shutOut = false;/*** The implementation of this Socket.*/SocketImpl impl;/*** Are we using an older SocketImpl?*/
private boolean oldImpl = false;
构造方法:public Socket(String host, int port)throws UnknownHostException, IOException
创建一个socket连接到host上的port端口上。这个构造方法会调自己私有的构造方法,这个私有的方法就有设置impl.
/*** Creates a stream socket and connects it to the specified port
* number on the named host.
*
* If the specified host is {@codenull} it is the equivalent of
* specifying the address as
* {@linkjava.net.InetAddress#getByName InetAddress.getByName}{@code(null)}.
* In other words, it is equivalent to specifying an address of the
* loopback interface.
*
* If the application has specified a server socket factory, that
* factory's {@codecreateSocketImpl} method is called to create
* the actual socket implementation. Otherwise a "plain" socket is created.
*
* If there is a security manager, its
* {@codecheckConnect} method is called
* with the host address and {@codeport}
* as its arguments. This could result in a SecurityException.
*
*@paramhost the host name, or {@codenull} for the loopback address.
*@paramport the port number.
*
*@exceptionUnknownHostException if the IP address of
* the host could not be determined.
*
*@exceptionIOException if an I/O error occurs when creating the socket.
*@exceptionSecurityException if a security manager exists and its
* {@codecheckConnect} method doesn't allow the operation.
*@exceptionIllegalArgumentException if the port parameter is outside
* the specified range of valid port values, which is between
* 0 and 65535, inclusive.
*@seejava.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
*@seejava.net.SocketImpl
*@seejava.net.SocketImplFactory#createSocketImpl()
*@seeSecurityManager#checkConnect*/
public Socket(String host, intport)throwsUnknownHostException, IOException
{this(host != null ? newInetSocketAddress(host, port) :new InetSocketAddress(InetAddress.getByName(null), port),
(SocketAddress)null, tru