-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServer.java
More file actions
78 lines (70 loc) · 1.9 KB
/
HttpServer.java
File metadata and controls
78 lines (70 loc) · 1.9 KB
1
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/*
* http://habrahabr.ru/post/69136/
* êàê çàïóñòèòü:
* 1. cmd: cd path-to-file\...
* 2. javac HttpServer.java
* 3. java -cp . HttpServer
* 4. http://localhost:8080/
*/
public class HttpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
while(true) {
Socket socket = serverSocket.accept();
System.err.println("Client accepted");
new Thread(new SocketProcessor(socket)).start();
}
}
private static class SocketProcessor implements Runnable {
private Socket s;
private InputStream is;
private OutputStream os;
private SocketProcessor(Socket s) throws IOException {
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
}
@Override
public void run() {
try {
readInputHeaders();
writeResponse("<html><body><h1>Hello from Habra</h1></body></html>");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.err.println("Client processing finished");
}
private void readInputHeaders() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while(true) {
String s = br.readLine();
if(s == null || s.trim().length() == 0) {
break;
}
}
}
private void writeResponse(String s) throws IOException {
String response = "HTTP/1.1 200 OK\r\n" +
"Server: MikeServer/2015-08-19\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + s.length() + "\r\n" +
"Connection: close\r\n\r\n";
String result = response + s;
os.write(result.getBytes());
os.flush();
}
}
}