forked from patniemeyer/learningjava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargerHttpd.java
More file actions
144 lines (131 loc) · 4.31 KB
/
Copy pathLargerHttpd.java
File metadata and controls
144 lines (131 loc) · 4.31 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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.regex.*;
public class LargerHttpd
{
Selector clientSelector;
public void run( int port, int threads ) throws IOException
{
clientSelector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
InetSocketAddress sa = new InetSocketAddress( InetAddress.getLoopbackAddress(), port );
ssc.socket().bind( sa );
ssc.register( clientSelector, SelectionKey.OP_ACCEPT );
Executor executor = Executors.newFixedThreadPool( threads );
while ( true ) {
try {
while ( clientSelector.select(100) == 0 );
Set<SelectionKey> readySet = clientSelector.selectedKeys();
for(Iterator<SelectionKey> it=readySet.iterator(); it.hasNext();)
{
final SelectionKey key = it.next();
it.remove();
if ( key.isAcceptable() ) {
acceptClient( ssc );
} else {
key.interestOps( 0 );
executor.execute( new Runnable() {
public void run() {
try {
handleClient( key );
} catch ( IOException e) { System.out.println(e); }
}
} );
}
}
} catch ( IOException e ) { System.out.println(e); }
}
}
void acceptClient( ServerSocketChannel ssc ) throws IOException
{
SocketChannel clientSocket = ssc.accept();
clientSocket.configureBlocking(false);
SelectionKey key = clientSocket.register( clientSelector, SelectionKey.OP_READ );
HttpdConnection client = new HttpdConnection( clientSocket );
key.attach( client );
}
void handleClient( SelectionKey key ) throws IOException
{
HttpdConnection client = (HttpdConnection)key.attachment();
if ( key.isReadable() ) {
client.read( key );
} else {
client.write( key );
}
clientSelector.wakeup();
}
public static void main( String argv[] ) throws IOException {
//new LargerHttpd().run( Integer.parseInt(argv[0]), 3/*threads*/ );
new LargerHttpd().run( 1235, 3/*threads*/ );
}
}
class HttpdConnection {
static Charset charset = Charset.forName("8859_1");
static Pattern httpGetPattern = Pattern.compile("(?s)GET /?(\\S*).*");
SocketChannel clientSocket;
ByteBuffer buff = ByteBuffer.allocateDirect( 64*1024 );
String request;
String response;
FileChannel file;
int filePosition;
HttpdConnection ( SocketChannel clientSocket ) {
this.clientSocket = clientSocket;
}
void read( SelectionKey key ) throws IOException {
if ( request == null && (clientSocket.read( buff ) == -1
|| buff.get( buff.position()-1 ) == '\n' ) )
processRequest( key );
else
key.interestOps( SelectionKey.OP_READ );
}
void processRequest( SelectionKey key ) {
buff.flip();
request = charset.decode( buff ).toString();
Matcher get = httpGetPattern.matcher( request );
if ( get.matches() ) {
request = get.group(1);
if ( request.endsWith("/") || request.equals("") )
request = request + "index.html";
System.out.println( "Request: "+request);
try {
file = new FileInputStream ( request ).getChannel();
} catch ( FileNotFoundException e ) {
response = "404 Object Not Found";
}
} else
response = "400 Bad Request" ;
if ( response != null ) {
buff.clear();
charset.newEncoder().encode(
CharBuffer.wrap( response ), buff, true );
buff.flip();
}
key.interestOps( SelectionKey.OP_WRITE );
}
void write( SelectionKey key ) throws IOException {
if ( response != null ) {
clientSocket.write( buff );
if ( buff.remaining() == 0 )
response = null;
} else if ( file != null ) {
int remaining = (int)file.size()-filePosition;
long sent = file.transferTo( filePosition, remaining, clientSocket);
if ( sent >= remaining || remaining <= 0 ) {
file.close();
file = null;
} else
filePosition += sent;
}
if ( response == null && file == null ) {
clientSocket.close();
key.cancel();
} else
key.interestOps( SelectionKey.OP_WRITE );
}
}