1.实现HTTP 1.0 GET命令的客户端
1
/** *//**
2
*这是一个简单的HTTP客户端程序
3
* @author wangliang
4
*/
5
package http;
6
7
import java.io.BufferedInputStream;
8
import java.io.BufferedReader;
9
import java.net.Socket;
10
import java.io.FileOutputStream;
11
import java.io.IOException;
12
import java.io.InputStreamReader;
13
import java.io.PrintWriter;
14
import java.io.File;
15
import java.util.StringTokenizer;
16
17
/** *//**
18
*这是一个简单的HTTP客户端程序,你可以实现HTTP1.0的GET命令
19
* @author wangliang
20
*/
21
22
23
public class Client
{
24
25
public static void main(String args[]) throws Exception
{
26
if (args.length == 2)
{
27
Client client = new Client(args[0], Integer.parseInt(args[1]));
28
client.run();
29
} else if (args.length == 0)
{
30
Client client2 = new Client("www.whu.edu.cn", 80);
31
client2.run();
32
} else
{
33
System.out.println("ERROR.You should input as below");
34
System.out.println("java Client host port or java Client");
35
}
36
}
37
String host;
38
int port;
39
40
public Client(String host, int port)
{
41
this.host = host;
42
this.port = port;
43
}
44
45
/** *//**与服务器建立连接,发送GET请求命令*/
46
public void run()
{
47
Socket socket;
48
BufferedInputStream in;
49
PrintWriter out;
50
try
{
51
socket = new Socket(host, port);
52
System.out.println(socket.getRemoteSocketAddress());
53
System.out.println("连接成功");
54
in = new BufferedInputStream(socket.getInputStream());
55
out = new PrintWriter(socket.getOutputStream(), true);
56
try
{
57
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
58
String userInput;
59
while ((userInput = stdIn.readLine()) != null)
{
60
if (userInput.equalsIgnoreCase("quit"))
{
61
System.out.println("关闭浏览器");
62
System.exit(0);
63
}
64
out.println(userInput);
65
out.println();
66
System.out.println(userInput);
67
int mark = 0;
68
int word = -1;
69
byte data[] = new byte[0];
70
byte data2[] = new byte[1000];
71
while ((word = in.read(data2, 0, 1000)) != -1)
{
72
byte temp[] = data;
73
data = new byte[data.length + word];
74
System.arraycopy(temp, 0, data, 0, temp.length);
75
System.arraycopy(data2, 0, data, temp.length, word);
76
}
77
for (int i = 0; i < data.length; i++)
{
78
if (data[i] == 13 && data[i + 1] == 10 && data[i + 2] == 13 && data[i + 3] == 10)
{
79
mark = i + 4;
80
break;
81
}
82
}
83
byte head[] = new byte[mark];
84
System.arraycopy(data, 0, head, 0, mark);
85
System.out.println("头文件:");
86
System.out.println(new String(head));
87
byte file[] = new byte[data.length - mark];
88
System.arraycopy(data, mark, file, 0, data.length - mark);
89
save(userInput, file);
90
//重新建立连接
91
System.out.println("重新建立连接");
92
socket = new Socket(host, port);
93
System.out.println(socket.getRemoteSocketAddress());
94
System.out.println("连接成功");
95
in = new BufferedInputStream(socket.getInputStream());
96
out = new PrintWriter(socket.getOutputStream(), true);
97
}
98
99
} catch (IOException e1)
{
100
e1.printStackTrace();
101
}
102
} catch (IOException e2)
{
103
System.out.println("连接失败");
104
e2.printStackTrace();
105
System.exit(0);
106
}
107
}
108
109
/** *//**保存get获取的文件*/
110
void save(String userInput, byte bf[])
{
111
StringTokenizer t = new StringTokenizer(userInput, " ");
112
if (t.countTokens() < 2)
{
113
return;
114
}
115
t.nextToken();
116
String t2 = t.nextToken();
117
int last = t2.lastIndexOf("/");
118
//获取文件名
119
String filename = t2.substring(last + 1, t2.length());
120
if (filename.equals(""))
{
121
filename = "index.html";
122
}
123
String dir = t2.substring(0, last);
124
//获取文件的目录
125
126
File dirs = new File(host + dir);
127
dirs.mkdirs();
128
File file = new File(dirs, filename);
129
try
{
130
FileOutputStream out = new FileOutputStream(file);
131
out.write(bf);
132
System.out.println("文件" + filename + "成功保存到文件夹" + host + dir);
133
} catch (Exception e)
{
134
// TODO Auto-generated catch block
135
System.out.println("文件保存失败");
136
}
137
}
138
}
139
直接打印头文件,保存GET的文件;没有分析响应头的代码
2.简单的每请求线程模型服务器
ThreadedServer监听一个端口,对每个Socket请求生成一个Handler线程进行处理,服务器文件放在一个www文件夹中
1
/**//*
2
* To change this template, choose Tools | Templates
3
* and open the template in the editor.
4
*/
5
package http;
6
7
import java.net.ServerSocket;
8
9
/**//*
10
* To change this template, choose Tools | Templates
11
* and open the template in the editor.
12
*/
13
import java.net.Socket;
14
15
/** *//**
16
*这是一个多线程简单的HTTP服务器程序,它可以接受HTTP1.0的GET命令
17
* @author wangliang
18
*/
19
public class ThreadedServer
{
20
21
String serverName;
22
String Version;
23
int serverport;
24
25
public static void main(String args[])
{
26
ThreadedServer server = new ThreadedServer("HTTPSServer", "1.0", 801);
27
server.run();
28
}
29
30
public ThreadedServer(String name, String version, int port)
{
31
serverName = name;
32
Version = version;
33
serverport = port;
34
}
35
36
/** *//**为客户端的每个请求启动一个线程处理用户的请求*/
37
public void run()
{
38
int count=1;
39
System.out.println(serverName + " version:" + Version);
40
try
{
41
ServerSocket server = new ServerSocket(serverport);
42
do
{
43
Socket client = server.accept();
44
(new Handler(client)).start();
45
System.out.println("Now " + (count++) + " requests received!");
46
} while (true);
47
} catch (Exception e)
{
48
e.printStackTrace();
49
System.exit(1);
50
}
51
}
52
}
53

/**//*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package http;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;


/**//*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Date;
import java.util.StringTokenizer;


/** *//**
*ThreadedServer的帮助类,处理用户的每一个请求
* @author wangliang
*/

public class Handler extends Thread
{
private Socket connectionSocket;

public Handler(Socket socket)
{
this.connectionSocket=socket;
}

public void run()
{

try
{
String fileName="";
String requestMessageLine;
BufferedReader inFromClient=
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient=
new DataOutputStream(connectionSocket.getOutputStream());
requestMessageLine=inFromClient.readLine();
StringTokenizer tokenizedLine=
new StringTokenizer(requestMessageLine);

if(tokenizedLine.nextToken().equals("GET"))
{
fileName=tokenizedLine.nextToken();
if(fileName.equals("/")==true) fileName="index.html";

else if(fileName.startsWith("/")==true)
{
fileName=fileName.substring(1);

if (fileName.endsWith("/"))
{
fileName = fileName + "index.html";
}
}
File file=new File("www/"+fileName);

if (file.exists()&&file.isFile())
{
int numOfBytes=(int)file.length();
FileInputStream inFile=new FileInputStream(file);
byte[] fileInBytes=new byte[numOfBytes];
inFile.read(fileInBytes);
outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n");
outToClient.writeBytes("Date:"+new Date()+"\r\n");
outToClient.writeBytes("Server:My client\r\n");
if(fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type:image/jpeg\r\n");
if(fileName.endsWith(".html"))
outToClient.writeBytes("Content-Type:text/html\r\n");
outToClient.writeBytes("Content-Length:"+
numOfBytes+"\r\n");
outToClient.writeBytes("\r\n");
outToClient.write(fileInBytes,0,numOfBytes);
connectionSocket.close();
}

else
{
String notfound="<html><head><title>Not Found</title></head><body><h1>Error 404-file not found</h1></body></html>";
outToClient.writeBytes("HTTP/1.0 404 no found\r\n");
outToClient.writeBytes("Date:"+new Date()+"\r\n");
outToClient.writeBytes("Server:My client\r\n");
outToClient.writeBytes("Content_Type:text/html\r\n");
outToClient.writeBytes("Content_Length:"+notfound.length()+2+"\r\n");
outToClient.writeBytes(notfound);
outToClient.close();
}
}
else System.out.println("Bad Request Message");
}

catch(IOException e)
{
System.out.println("IOException occured.");
e.printStackTrace();
}
}
}
