文档介绍:a 网络编程(下) ID:SCSJ002-J2SE Java 网络编程(下) ? URL 类?利用 NIO 实现非阻塞 Socket 通信 20 11 -05-0 9 2 URL ? URL(Uniform Resource Locator)---- 统一资源定位器,表示 上某一资源的地址。? URL 组成: 协议名和资源名? protocol:resourceName ? URL 举例:? ? ? ftp://files. 20 11 -05-0 9 3 URL 类?常用构造方法? public URL(String spec); ?例如: URL u1 = new URL( “/home/ ”); ? public URL(URL context, String spec); ?例如: URL u2 = new URL(u1, “ ”); ? public URL(String protocol, String host, String file); ?例如: URL u3 = new URL( “ http ”, “ ”, “ developers/ ” ); ? public URL (String protocol, String host, int port, String file); ?例如: URL u4 = new URL( “ http ”, “ ”, 80, “ developers/ ” ); 20 11 -05-0 9 4 URL 类? openConnection ? public URLConnection openConnection() throws IOException 20 11 -05-0 9 5 URLConnection getInputStream ? public InputStream getInputStream() throws IOException getOutputStream ? public OutputStream getOutputStream() throws IOException URLConnection conn = (); 20 11 -05-0 9 6 URL 例子(案例 13-4 ) try { URL url = new URL("/home/"); URLConnection conn = (); BufferedReader reader = new BufferedReader (new InputStreamReader (())); String s; while((s = ()) != null){ System .(s); } } catch ( MalformedURLException e) { (); }catch ( IOException e) { (); } 20 11 -05-0 9 7 Socket NIO 通信模型 Client Server Client Client SELECTOR 20 11 -05-0 9 8 和 Socket 非阻塞通信相关的 NIO 类? Selector :所有非阻塞技术的主要对象,它监视着已注册的 Selectable 通道,当某个通道有事件发生的时候,它将触发会触发一个事件。? ServerSocketChannel/SocketChannel :用于提供非阻塞 Socket 通信? SelectionKey :每个“键”代表一个单独的客户端子请求并包含识别客户端和请求类型的信息? InetSocketAddress :一个用于表示 Socket IP 地址和端口号相结合的网络地址 20 11 -05-0 9 9 NIO Socket 通信例子(案例 13-5 ) ? ? 20 11 -05-0 9 10