J2SE 1.4 引入 Inet4Address 和 Inet6Address 兩個 InetAddress 子類,支援新一代網際網路協議 IPv6。Inet4Address 維持舊式點分十進制(如 127.0.0.1),Inet6Address 採用冒號分隔格式(如 0:0:0:0:0:0:0:1 為回環地址)。應用程式可同時支援兩種寻址方案。底層平台需支援 IPv6:Solaris 8+、Linux 2.1.2+ (RedHat 6.1+) 支援,Windows 2000 僅有限實現,期待後續版本完善。
新增 java.net.URI 類,可視為無協議處理器的 URL。URI 格式:[scheme:][//authority][path][?query][#fragment],authority 可含用戶資訊、主機、端口。URI 類提供 getter 方法解析各部分。過去無協議處理器的字串(如 jdbc:database)只能當字串處理,現可用 URI 類規範表示。
新 NetworkInterface 介面讓 Java 程式無需本地代碼即可枚舉網卡資訊。多宿主機器可有多張網卡,各有獨立連接、名稱、地址。可指定發送多點廣播用哪張網卡,或檢查連接狀態。範例代碼:
import java.net.*;
import java.util.Enumeration;
public class Nets {
public static void main(String args[]) throws SocketException {
Enumeration e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface net = (NetworkInterface)e.nextElement();
System.out.println("Names: " + net.getName() + " / " + net.getDisplayName());
Enumeration e2 = net.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress addr = (InetAddress)e2.nextElement();
System.out.println("\tAddress: " + addr.getHostAddress());
}
}
}
}
輸出範例顯示回環介面 (lo) 與乙太網卡 (eth0) 及其 IP。
配合 Merlin 新 I/O (NIO),網絡類支援非阻塞操作。InetSocketAddress 和 SocketAddress 允許打開連接並在真正連接前設置選項。基本序列:
String hostname = ...;
int port = ...;
SocketAddress socketAddress = new InetSocketAddress(host, port);
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(socketAddress);
新增 javax.net.ssl 套件,提供 Java Secure Socket Extension (JSSE) 功能,即 HTTPS 的 SSL 支援,無需標準擴展庫。透過 SSLSocketFactory 獲取 SSL 套接字即自動建立安全連接(服務器需支援)。使用方式與普通套接字無異。範例連接指定站點或 Verisign 獲取首頁:
import java.io.*;
import java.net.*;
import javax.net.*;
import javax.net.ssl.*;
public class SslSample {
static final int HTTPS_PORT = 443;
public static void main(String args[]) throws IOException {
String hostname = (args.length == 0) ? "www.verisign.com" : args[0];
SocketFactory factory = SSLSocketFactory.getDefault();
Socket socket = factory.createSocket(hostname, HTTPS_PORT);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.print("GET / HTTP/1.0\r\n\r\n");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) System.out.println(line);
pw.close(); br.close(); socket.close();
}
}
亦可用 HttpsURLConnection 類似 URLConnection 方式。
URLEncoder/URLDecoder 支援程式員指定字符集編解碼。URLConnection 標頭處理增強,支援直接獲取/添加標頭。Merlin 為標準 Java 編程添加許多網絡功能,有的長期存在終納入標準版,有的為全新升級。隨著 Java 技術擴展,跟上新特性需持續探索。