TCP Socket

============================================== InetAddress============================================
InetAddress 类代表一个主机(包括hostName和IP),这个类的构造方法不可用,你可以通过以下几个方法来获取此类实例:
/*
    如果为getByName("www.163.com") 则这个方法会去访问DNS服务器,如果出错还会抛出异常;
    InetAddress为存储一些 hostName<-->IP 对(如果提供hostName没有找到IP,这种错误的情形也会存储,不过只会存10s),这样就不会每次去查询DNS服务器,节省时间;
    也可以这样: getByName("202.12.33.12") 这时不会去查询 DNS服务器(hostName默认为IP),只有在调用 getHostName()时才会去查询,而且即使查询不到也不会抛异常
*/
public static InetAddress getByName(String hostName) throws UnknownHostException

/*
    一个主机名对应多个IP地址,如www.microsoft.com 对应好多个IP
*/
public static InetAddress[] getAllByName(String hostName) throws UnknownHostException
//得到运行此程序的本机地址
public static InetAddress getLocalHost( ) throws UnknownHostException

其它三个get方法:
public String getHostName( )
public byte[] getAddress( )
public String getHostAddress( )
有一个特殊的 InetAddress 代表了本地地址、多播地址等,InetAddress类提供了一些静态方法去检测:
public boolean isAnyLocalAddress( )
public boolean isLoopbackAddress( )
=============================================================================================================

================================== NetworkInterface================================
NetworkInterface 代表一块物理网卡(或虚拟的)

/* 每个平台上 name是不确定的,如unix下的 eth0,而Windows下的LK1000(硬件设备名) */
public static NetworkInterface getByName(String name) throws SocketException
public static NetworkInterface getByInetAddress(InetAddress address) throws SocketException 用法如下:
try {
  InetAddress local = InetAddress.getByName("127.0.0.1");
  NetworkInterface ni = NetworkInterface.getByName(local);
  if (ni == null) {
    System.err.println("That's weird. No local loopback address.");
  }
}
catch (SocketException ex) {
  System.err.println("Could not list sockets." );
}
catch (UnknownHostException ex) {
  System.err.println("That's weird. No local loopback address.");
}

public static NetworkInterface getByInetAddress(InetAddress address) throws SocketException 用法如下:
public class InterfaceLister {
    public static void main(String[] args) throws Exception {
      Enumeration interfaces = NetworkInterface.getNetworkInterfaces( );
      while (interfaces.hasMoreElements( )) {
        NetworkInterface ni = (NetworkInterface) interfaces.nextElement( );
        System.out.println(ni);               
      }       
    }
}
/*输出:
name:eth1 (eth1) index: 3 addresses:
/192.168.210.122;
name:eth0 (eth0) index: 2 addresses:
/152.2.210.122;
name:lo (lo) index: 1 addresses:
/127.0.0.1;
You can see that this host has two separate Ethernet cards plus the local loopback address
*/
其它的方法:
public String getName( )
==================================================================================
=========================================== URL====================================
URL 使用 策略设计模式, Protocol handlers are strategies... 有时间研究一下
URL可以被分成几个部分,如protocol,hostname,query等.
URL内建的支持了一些常见的协议,如果想让URL支持一些自定的协议就要使用 Protocol handler.
构造函数:
public URL(String url) throws MalformedURLException

public URL(String protocol, String hostname, String file) 例如:
URL u = new URL("http", "www.eff.org", "/blueribbon.html#intro");
public URL(String protocol, String host, int port, String file) throws MalformedURLException

public URL(URL base, String relative) throws MalformedURLException 例子:
URL u1 = new URL("http://www.ibiblio.org/javafaq/index.html");
URL u2 = new URL (u1, "mailinglists.html"); //会变为 http://www.ibiblio.org/javafaq/mailinglists.html
public URL(URL base, String relative, URLStreamHandler handler) throws MalformedURLException

public InputStream openStream( ) throws IOException //只返回Http正文,不包含头信息
public URLConnection openConnection( ) throws IOException //可以通过URLConnection获取HTTP的所有信息
/*
    根据Http的 Content-Type 声明的类型返回不同的Class
*/
public Object getContent( ) throws IOException
=======================================================================================
================================ URI===========================================
URI只表示一个文件的位置,而不提供获取文件的方法,同时 URI包括URL和URN
==============================================================================

=============================== Socket======================================
//以下四条是Socket完成的
Connect to a remote machine
Send data
Receive data
Close a connection
//以下三条是ServerSocket完成的
Bind to a port
Listen for incoming data
Accept connections from remote machines on the bound port

一个正常的Socket程序的交互过程为:
1、The program creates a new socket with a constructor.

2、The socket attempts to connect to the remote host.

3、Once the connection is established, the local and remote hosts get input and output streams from the socket and use those streams to send data to each other. This connection is full-duplex; both hosts can send and receive data simultaneously. What the data means depends on the protocol; different commands are sent to an FTP server than to an HTTP server. There will normally be some agreed-upon hand-shaking followed by the transmission of data from one to the other.

4、When the transmission of data is complete, one or both sides close the connection. Some protocols, such as HTTP 1.0, require the connection to be closed after each request is serviced. Others, such as FTP, allow multiple requests to be processed in a single connection

//建立一个与远程机器的连接
public Socket(String host, int port) throws UnknownHostException, IOException
public Socket(InetAddress host, int port) throws IOException
//这个构造函数以后详细研究
protected Socket(SocketImpl impl)
//得到连接的远程的 主机
public InetAddress getInetAddress( )
//得到远程主机 port
public int getPort( )
public int getLocalPort( )
public InetAddress getLocalAddress( )

//得到 InputStream 后你就可以随便操作啦
public InputStream getInputStream( ) throws IOException

public void close( ) throws IOException
public boolean isClosed( ) // Java 1.4
public boolean isConnected( ) // Java 1.4  只要socket连接上就返回true,即使它已经被closed
boolean connected = socket.isConnected( ) && ! socket.isClosed( ); //判断是否socket正在连接
public boolean isBound( ) // Java 1.4 Socket在local机器上是否成功
public void shutdownInput( ) throws IOException  // Java 1.3
public void shutdownOutput( ) throws IOException // Java 1.3 作用如下:
Socket connection = null;
try {
  connection = new Socket("www.oreilly.com", 80);
  Writer out = new OutputStreamWriter(
  connection.getOutputStream( ), "8859_1");
  out.write("GET / HTTP 1.0\r\n\r\n");
  out.flush( );
  //HTTP协议的客户端在输出完成后不会再输出,所以关闭它
  connection.shutdownOutput( );
  // read the response...
}
catch (IOException ex) {
}
finally {
  try {
    if (connection != null) connection.close( );
   }
   catch (IOException ex) {}
}
//和 isConnected() isClosed() 使用方法相似
public boolean isInputShutdown( )   // Java 1.4
public boolean isOutputShutdown( )  // Java 1.4

Setting Socket Options 用来设置native层Socket如何接受和发送数据,有以下几个选项:
/*
不缓冲,很小的包也要发送,具体待时间研究
public void setTcpNoDelay(boolean on) throws SocketException
public boolean getTcpNoDelay( ) throws SocketException
*/
TCP_NODELAY
SO_BINDADDR
/*
如果millisecnods设置成0,则无限等待,这也是默认的行为
public void setSoTimeout(int milliseconds) throws SocketException
publicint getSoTimeout( ) throws SocketException
当你从Socket得到 InputStream,然后进行 read()时 read会阻塞,你可以通过这个字段设置阻塞的时间
超过时间后会抛出 IOException异常,你需要捕获异常,过一会时间再读
*/
SO_TIMEOUT
/*
Socket关闭之后剩下的没有发送完的数据怎么处理?
*/
SO_LINGER
SO_SNDBUF (Java 1.2 and later) //Socket Option Send Buffer Size
/*
对于传送大文件,缓冲越大越好;但对于游戏这种小流量缓冲要小一点,以提高速度
*/
SO_RCVBUF (Java 1.2 and later)
/*
每隔一段时间向服务器发送一个小包以确定服务器可用,这样如果服务器死掉后,客户端可以及时关闭自己
*/
SO_KEEPALIVE (Java 1.3 and later)
OOBINLINE (Java 1.4 and later)
/*
Socket关闭后,port 不会立即释放port,这对于某些使用明确端口的程序有影响
对于随即使用的port,此标记不太有用
*/
SO_REUSEADDR 
=====================================================================================================
============================================ SocketAddress========================

是一个工具类,用法如下:

Socket socket = new Socket("www.yahoo.com", 80);
SocketAddress yahoo = socket.getRemoteSocketAddress( );
socket.close( );

Later, you could reconnect to Yahoo using this address:

socket = new Socket( );

socket.connect(yahoo);

SocketAddress sa = new INetSocketAddress(80);
=================================================================================

================================ ServerSocket=====================================
构造函数:
public ServerSocket(int port, int queueLength) throws IOException, BindException
这个构造函数比较特殊,它没有bind到一个特定的 port,可以在以后 bind(SocketAddress endpoint)
public ServerSocket( ) throws IOException // Java 1.4

public InetAddress getInetAddress( ) //得到服务器本地的InetAddress
public int getLocalPort( )


有一篇博文是专门关于ServerSocket可以看一下

=================================================================================
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值