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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
package com.hackingroomba.roombacomm.net;
import java.net.*;
import java.io.*;
public class TextHttpServer {
int port = 6767;
/*
String cmds[] =
{
"reset", // zero args
"stop", // zero args
"goforward", // one optional arg
"gobackward", // one optional arg
"spinleft", // one optional arg
"spinright", // one optional arg
"beep", // two args
};
*/
// the shutdown command received
private boolean shutdown = false;
public static void main(String[] args) {
TextHttpServer server = new TextHttpServer();
server.await();
}
public void await() {
System.out.println("awaiting connections on port "+port+"...");
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port, 1, null);
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// Loop waiting for a request
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept(); // this blocks
input = socket.getInputStream();
output = socket.getOutputStream();
StringBuffer request = parseRequest( input );
String uristr = parseUri( request.toString() );
System.out.println("uristr: "+uristr);
URI uri = new URI( uristr );
System.out.println("path:"+uri.getPath()+", query:"+uri.getQuery());
// Close the socket
socket.close();
} catch (Exception e) {
e.printStackTrace();
//System.exit(1);
}
}
}
public StringBuffer parseRequest(InputStream input) {
// Read a set of characters from the socket
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
}
catch (IOException e) {
e.printStackTrace();
i = -1;
}
for (int j=0; j<i; j++) {
request.append((char) buffer[j]);
}
System.out.print(request.toString());
return request;
}
private String parseUri(String requestString) {
int index1, index2;
index1 = requestString.indexOf(' ');
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
}
}
|