| import java.io.*; import java.net.*; /** * 一个简单的从服务器取回一个HTML页面的程序 * 注意:merlin是本地机器的名字 */ public class SimpleWebClient { public static void main(String args[]) { try { // 打开一个客户端socket连接 Socket clientSocket1 = new Socket("merlin", 80); System.out.println("Client1: " + clientSocket1); // 取得一个网页 getPage(clientSocket1); } catch (UnknownHostException uhe) { System.out.println("UnknownHostException: " + uhe); } catch (IOException ioe) { System.err.println("IOException: " + ioe); } } /** *通过建立的连接请求一个页面,显示回应然后关闭socket */ public static void getPage(Socket clientSocket) { try { // 需要输入和输出流 DataOutputStream outbound = new DataOutputStream( clientSocket.getOutputStream() ); DataInputStream inbound = new DataInputStream( clientSocket.getInputStream() ); // 向服务器发出HTTP请求 outbound.writeBytes("GET / HTTP/1.0 "); // 读出回应 String responseLine; while ((responseLine = inbound.readLine()) != null) { // 把每一行显示出来 System.out.println(responseLine); if ( responseLine.indexOf("") != -1 ) break; } // 清除 outbound.close(); inbound.close(); clientSocket.close(); } catch (IOException ioe) { System.out.println("IOException: " + ioe); } } } |