本文實現了一個簡單的多線程HTTP服務器。接收HTTP GET請求,然后返回簡單的文本信息。
后期會豐富這個服務器,實現更多的功能,例如:
1. 支持POST方式提交
2. 支持二進制的流傳送
3. 支持線程池處理
4. 采用NIO非阻塞形式實現
運行這個程序啟動服務器,然后在瀏覽器地址欄輸入:http://localhost:8888/,即可看到返回結果。
友情提醒:本博文章歡迎轉載,但請注明出處:陳新漢
后期會豐富這個服務器,實現更多的功能,例如:
1. 支持POST方式提交
2. 支持二進制的流傳送
3. 支持線程池處理
4. 采用NIO非阻塞形式實現
1
package thread;
2
3
import java.io.BufferedReader;
4
import java.io.IOException;
5
import java.io.InputStream;
6
import java.io.InputStreamReader;
7
import java.io.OutputStream;
8
import java.io.PrintWriter;
9
import java.net.ServerSocket;
10
import java.net.Socket;
11
12
/**
13
* Copyright (C): 2009
14
* @author 陳新漢
15
* Jun 27, 2009 2:39:39 PM
16
*/
17
18
/**
19
* Threaded Network Server
20
* 這是一個簡單的多線程HTTP服務器
21
* 采用多線程來處理高并發的用戶請求
22
*/
23
public class HttpServer {
24
public static void main(String [] args){
25
HttpServer hs=new HttpServer();
26
int i=1, port=8888;
27
Socket received=null;
28
try{
29
ServerSocket server=new ServerSocket(port);
30
while(true){
31
received=server.accept();
32
if(received!=null){
33
hs.new ProcessThread(i++,received).start();
34
}
35
}
36
}catch(IOException e){
37
e.printStackTrace();
38
}
39
}
40
41
class ProcessThread extends Thread
42
{
43
private int thread_number=0;
44
private Socket received=null;
45
46
public ProcessThread(int thread_number, Socket received) {
47
super();
48
this.thread_number = thread_number;
49
this.received = received;
50
}
51
52
public void run() {
53
System.out.println("第"+thread_number+"個處理線程啟動了……");
54
if(received!=null){
55
try{
56
System.out.println("連接用戶的地址:"+received.getInetAddress().getHostAddress());
57
InputStream in=received.getInputStream();
58
BufferedReader d= new BufferedReader(new InputStreamReader(in));
59
String result=d.readLine();
60
while(result!=null && !result.equals("")){
61
System.out.println(result);
62
result=d.readLine();
63
}
64
OutputStream out=received.getOutputStream();
65
PrintWriter outstream=new PrintWriter(out,true);
66
String msg1="<html><head><title></title></head><body><h1>收到!</h1></body></html>";
67
outstream.println("HTTP/1.0 200 OK");//返回應答消息,并結束應答
68
outstream.println("Content-Type:text/html;charset=GBK");
69
outstream.println();// 根據 HTTP 協議, 空行將結束頭信息
70
outstream.println(msg1);
71
outstream.flush();
72
outstream.close();
73
}catch(IOException e){
74
e.printStackTrace();
75
}finally{
76
try{
77
received.close();
78
}catch(IOException e){
79
e.printStackTrace();
80
}
81
}
82
}
83
}
84
}
85
}
86

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

運行這個程序啟動服務器,然后在瀏覽器地址欄輸入:http://localhost:8888/,即可看到返回結果。
友情提醒:本博文章歡迎轉載,但請注明出處:陳新漢