-
Notifications
You must be signed in to change notification settings - Fork 3
/
TestServerSocket.java
65 lines (54 loc) · 1.97 KB
/
TestServerSocket.java
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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
/*
* Reference: http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
*/
public class TestServerSocket {
public static void main(String [] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8080);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String inputLine = null;
String data = "";
inputLine = in.readLine();
while (!inputLine.equals("")) {
data += inputLine + "\n";
inputLine = in.readLine();
}
System.out.println("Receiving data done..");
System.out.println("Sending response..");
if (data.contains("GET")) {
doGet(data, out);
}
System.out.println("Server closing.");
clientSocket.close();
serverSocket.close();
System.out.println("Done.");
}
private static void doGet(String data, PrintWriter out) throws Exception {
data += "Expires: " + getExpiresDate() + "\n";
out.println(data);
}
private static String getExpiresDate() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
long currentTime = calendar.getTimeInMillis();
long tenMinutes = 600000;
long currentPlusTen = currentTime + tenMinutes;
calendar.setTimeInMillis(currentPlusTen);
String expires = dateFormat.format(calendar.getTime());
return expires;
}
}