用java socket实现了一个简单的http服务器, 可以处理GET, POST,以及带一个附件的multipart类型的POST。虽然中途遇到了很多问题, 不过通过在论坛和几个高手交流了一下,问题都解决了。如果你觉得程序有些地方看不明白,可以参看这个帖子:.
虽然解析http头不是很规范,本来应该用原始的字节流, 我采用了一个折衷的方案,用DataInputStream.
本代码的实用性==0,但是可以帮助很好地了解http协议,然后其他的应用层协议大都如此。
如果你从来都没有了解过http协议,建议先搜索阅读一下,或者你还可以用下面的代码来简单的看一看到底浏览器和服务器之间都相互发送了什么数据。
MyHttpClient.java:
1. package socket;
2.
3. import java.io.*;
4. import java.net.*;
5.
6. public class MyHttpClient {
7. public static void main(String[] args) throws Exception{
8. "www.baidu.com");
9. System.out.println(inet.getHostAddress());
10. new Socket(inet.getHostAddress(),80);
11. InputStream in = socket.getInputStream();
12. OutputStream out = socket.getOutputStream();
13. new BufferedReader(new InputStreamReader(in));
14. new PrintWriter(out);
15. "GET /home.html HTTP/1.1");//home.html是关于百度的页面
16. "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
17. "Accept-Language: en-us,zh-cn;q=0.5");
18. "Accept-Encoding: gzip, deflate");
19. "Host: www.baidu.com");
20. "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
21. "Connection: Keep-Alive");
22. writer.println();
23. writer.flush();
24. String line = reader.readLine();
25. while(line!=null){
26. System.out.println(line);
27. line = reader.readLine();
28. }
29. reader.close();
30. writer.close();
31. }
32. }
MyServer.java: 模拟server端接收浏览器的请求,然后把整个请求的报文打印出来。程序运行之后直接用浏览器测试。
1. package socket;
2.
3. import java.io.*;
4. import java.net.*;
5.
6. public class MyServer {
7. public static void main(String[] args) throws IOException{
8. new ServerSocket(8080);
9. while(true){
10. Socket socket = svrSocket.accept();
11. //足够大的一个缓冲区
12. byte[] buf = new byte[1024*1024];
13. InputStream in = socket.getInputStream();
14. int byteRead = in.read(buf, 0, 1024*1024);
15. new String(buf, 0, byteRead);
16. System.out.println(dataString);
17. in.close();
18. socket.close();
19. }
20. }
21. }
主程序MyHttpServer.
1. package socket;
2.
3. import java.io.*;
4. import java.net.*;
5. /**
6. * MyHttpServer 实现一个简单的HTTP服务器端,可以获取用户提交的内容
7. * 并给用户一个response
8. * 因为时间的关系,对http头的处理显得不规范
9. * 对于上传附件,暂时只能解析只上传一个附件而且附件位置在第一个的情况
10. * 转载请注明来自
11. * **/
12. public class MyHttpServer {
13. //服务器根目录,post.html, upload.html都放在该位置
14. public static String WEB_ROOT = "c:/root";
15. //端口
16. private int port;
17. //用户请求的文件的url
18. private String requestPath;
19. //mltipart/form-data方式提交post的分隔符,
20. private String boundary = null;
21. //post提交请求的正文的长度
22. private int contentLength = 0;
23.
24. public MyHttpServer(String root, int port) {
25. WEB_ROOT = root;
26. this.port = port;
27. null;
28. }
29. //处理GET请求
30. private void doGet(DataInputStream reader, OutputStream out) throws Exception {
31. if (new File(WEB_ROOT + this.requestPath).exists()) {
32. //从服务器根目录下找到用户请求的文件并发送回浏览器
33. new FileInputStream(WEB_ROOT + this.requestPath);
34. byte[] buf = new byte[fileIn.available()];
35. fileIn.read(buf);
36. out.write(buf);
37. out.close();
38. fileIn.close();
39. reader.close();
40. "request complete.");
41. }
42. }
43. //处理post请求
44. private void doPost(DataInputStream reader, OutputStream out) throws Exception {
45. String line = reader.readLine();
46. while (line != null) {
47. System.out.println(line);
48. line = reader.readLine();
49. if ("".equals(line)) {
50. break;
51. else if (line.indexOf("Content-Length") != -1) {
52. this.contentLength = Integer.parseInt(line.substring(line.indexOf("Content-Length") + 16));
53. }
54. //表明要上传附件, 跳转到doMultiPart方法。
55. else if(line.indexOf("multipart/form-data")!= -1){
56. //得multiltipart的分隔符
57. this.boundary = line.substring(line.indexOf("boundary") + 9);
58. this.doMultiPart(reader, out);
59. return;
60. }
61. }
62. //继续读取普通post(没有附件)提交的数据
63. "begin reading posted data......");
64. null;
65. //用户发送的post数据正文
66. byte[] buf = {};
67. int size = 0;
68. if (this.contentLength != 0) {
69. new byte[this.contentLength];
70. while(size<this.contentLength){
71. int c = reader.read();
72. byte)c;
73.
74. }
75. "The data user posted: " + new String(buf, 0, size));
76. }
77. //发送回浏览器的内容
78. "";
79. "HTTP/1.1 200 OK/n";
80. "Server: Sunpache 1.0/n";
81. "Content-Type: text/html/n";
82. "Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT/n";
83. "Accept-ranges: bytes";
84. "/n";
85. "<html><head><title>test server</title></head><body><p>post ok:</p>" + new String(buf, 0, size) + "</body></html>";
86. System.out.println(body);
87. out.write(response.getBytes());
88. out.write(body.getBytes());
89. out.flush();
90. reader.close();
91. out.close();
92. "request complete.");
93. }
94. //处理附件
95. private void doMultiPart(DataInputStream reader, OutputStream out) throws Exception {
96. "doMultiPart ......");
97. String line = reader.readLine();
98. while (line != null) {
99. System.out.println(line);
100. line = reader.readLine();
101. if ("".equals(line)) {
102. break;
103. else if (line.indexOf("Content-Length") != -1) {
104. this.contentLength = Integer.parseInt(line.substring(line.indexOf("Content-Length") + 16));
105. "contentLength: " + this.contentLength);
106. else if (line.indexOf("boundary") != -1) {
107. //获取multipart分隔符
108. this.boundary = line.substring(line.indexOf("boundary") + 9);
109. }
110. }
111. "begin get data......");
112. /*下面的注释是一个浏览器发送带附件的请求的全文,所有中文都是说明性的文字*****
113. <HTTP头部内容略>
114. ............
115. Cache-Control: no-cache
116. <这里有一个空行,表明接下来的内容都是要提交的正文>
117. -----------------------------7d925134501f6<这是multipart分隔符>
118. Content-Disposition: form-data; name="myfile"; filename="mywork.doc"
119. Content-Type: text/plain
120.
121. <附件正文>........................................
122. .................................................
123.
124. -----------------------------7d925134501f6<这是multipart分隔符>
125. Content-Disposition: form-data; name="myname"<其他字段或附件>
126. <这里有一个空行>
127. <其他字段或附件的内容>
128. -----------------------------7d925134501f6--<这是multipart分隔符,最后一个分隔符多两个->
129. ****************************************************************/
130. /**
131. * 上面的注释是一个带附件的multipart类型的POST的全文模型,
132. * 要把附件去出来,就是要找到附件正文的起始位置和结束位置
133. * **/
134. if (this.contentLength != 0) {
135. //把所有的提交的正文,包括附件和其他字段都先读到buf.
136. byte[] buf = new byte[this.contentLength];
137. int totalRead = 0;
138. int size = 0;
139. while (totalRead < this.contentLength) {
140. this.contentLength - totalRead);
141. totalRead += size;
142. }
143. //用buf构造一个字符串,可以用字符串方便的计算出附件所在的位置
144. new String(buf, 0, totalRead);
145. "the data user posted:/n" + dataString);
146. int pos = dataString.indexOf(boundary);
147. //以下略过4行就是第一个附件的位置
148. "/n", pos) + 1;
149. "/n", pos) + 1;
150. "/n", pos) + 1;
151. "/n", pos) + 1;
152. //附件开始位置
153. int start = dataString.substring(0, pos).getBytes().length;
154. 4;
155. //附件结束位置
156. int end = dataString.substring(0, pos).getBytes().length;
157. //以下找出filename
158. int fileNameBegin = dataString.indexOf("filename") + 10;
159. int fileNameEnd = dataString.indexOf("/n", fileNameBegin);
160. String fileName = dataString.substring(fileNameBegin, fileNameEnd);
161. /**
162. * 有时候上传的文件显示完整的文件名路径,比如c:/my file/somedir/project.doc
163. * 但有时候只显示文件的名字,比如myphoto.jpg.
164. * 所以需要做一个判断。
165. */
166. if(fileName.lastIndexOf("//")!=-1){
167. "//") + 1);
168. }
169. 0, fileName.length()-2);
170. new FileOutputStream("c://" + fileName);
171. fileOut.write(buf, start, end-start);
172. fileOut.close();
173. fileOut.close();
174. }
175. "";
176. "HTTP/1.1 200 OK/n";
177. "Server: Sunpache 1.0/n";
178. "Content-Type: text/html/n";
179. "Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT/n";
180. "Accept-ranges: bytes";
181. "/n";
182. "<html><head><title>test server</title></head><body><p>Post is ok</p></body></html>".getBytes());
183. out.flush();
184. reader.close();
185. "request complete.");
186. }
187.
188. public void service() throws Exception {
189. new ServerSocket(this.port);
190. "server is ok.");
191. //开启serverSocket等待用户请求到来,然后根据请求的类别作处理
192. //在这里我只针对GET和POST作了处理
193. //其中POST具有解析单个附件的能力
194. while (true) {
195. Socket socket = serverSocket.accept();
196. "new request coming.");
197. new DataInputStream((socket.getInputStream()));
198. String line = reader.readLine();
199. 0, 4).trim();
200. OutputStream out = socket.getOutputStream();
201. this.requestPath = line.split(" ")[1];
202. System.out.println(method);
203. if ("GET".equalsIgnoreCase(method)) {
204. "do get......");
205. this.doGet(reader, out);
206. else if ("POST".equalsIgnoreCase(method)) {
207. "do post......");
208. this.doPost(reader, out);
209. }
210. socket.close();
211. "socket closed.");
212. }
213. }
214. public static void main(String args[]) throws Exception {
215. new MyHttpServer("c:/root", 8080);
216. server.service();
217. }
218. }
测试文件post.html, upload.html都放在上面程序定义的WEB_ROOT下面。
post.html:处理普通的post请求
1. <html>
2. <head>
3. <title>test my server</title>
4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
5. </head>
6. <body>
7. <p>upload</p>
8. 来自<br>
9. <form name="UploadForm" method="post" action="http://localhost:8080/">
10. <input type="text" name="myname" /><br>
11. <select name="myage">
12. <option value="18">18</option>
13. <option value="20">20</option>
14. <option value="22">22</option>
15. </select><br>
16. <input type="submit"value="Sutmit">
17. </form>
18. </body>
19. </html>
upload.html:测试带附件的post请求
1. <head>
2. <title>my page</title>
3. <style>
4. table{
5. border-collapse: collapse;
6. }
7. </style>
8. </head>
9. <body>
10. 来自<br>
11. <form action='http://localhost:8080/' method='post' enctype='multipart/form-data'>
12. <input type='file' name='myfile' /><br>
13. <input type='submit' />
14. </form>
15. </body>