import java.net.*;
import java.io.*;
public class MyStreamSocket extends Socket {
private Socket socket;
private BufferedReader input;
private PrintWriter output;
MyStreamSocket(String acceptorHost,
int acceptorPort ) throws SocketException,
IOException{
socket = new Socket(acceptorHost, acceptorPort );
setStreams( );
}
MyStreamSocket(Socket socket) throws IOException {
this.socket = socket;
setStreams( );
}
private void setStreams( ) throws IOException{
// get an input stream for reading from the data socket
InputStream inStream = socket.getInputStream();
input =
new BufferedReader(new InputStreamReader(inStream));
OutputStream outStream = socket.getOutputStream();
// create a PrinterWriter object for character-mode output
output =
new PrintWriter(new OutputStreamWriter(outStream));
}
public void sendMessage(String message)
throws IOException {
output.println(message);
//The ensuing flush method call is necessary for the data to
// be written to the socket data stream before the
// socket is closed.
output.flush();
} // end sendMessage
public String receiveMessage( )
throws IOException {
// read a line from the data stream
String message = input.readLine( );
return message;
} //end receiveMessage
public void close( )
throws IOException {
socket.close( );
}
} //end class
//界面层?
public class HTTPClient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String host = "www.baidu.com"/*args[0]*/;
int port = 80/*Integer.parseInt(args[1])*/;
String fileName = "/index.html"/*args[2].trim()*/;
String request = "GET " + fileName +" HTTP/1.0\r\n";//Http请求行。具体百度谷歌之。
MyStreamSocket mySocket = new MyStreamSocket(host,port);
//System.out.println("connection made!");
mySocket.sendMessage(request);
String response;
response = mySocket.receiveMessage();
while (response != null) {
System.out.println(response);//打印服务器响应信息。包括状态行。头部内容。空行。web对象内容。
response = mySocket.receiveMessage();
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
//运行后的响应信息