Java Reference
In-Depth Information
selector
.
select
();
Iterator
<
SelectionKey
>
keys
=
selector
.
selectedKeys
().
iterator
();
while
(
keys
.
hasNext
())
{
SelectionKey
key
=
keys
.
next
();
keys
.
remove
();
try
{
if
(
key
.
isAcceptable
())
{
ServerSocketChannel
server
=
(
ServerSocketChannel
)
key
.
channel
();
SocketChannel
channel
=
server
.
accept
();
channel
.
configureBlocking
(
false
);
channel
.
register
(
selector
,
SelectionKey
.
OP_READ
);
}
else
if
(
key
.
isWritable
())
{
SocketChannel
channel
=
(
SocketChannel
)
key
.
channel
();
ByteBuffer
buffer
=
(
ByteBuffer
)
key
.
attachment
();
if
(
buffer
.
hasRemaining
())
{
channel
.
write
(
buffer
);
}
else
{
// we're done
channel
.
close
();
}
}
else
if
(
key
.
isReadable
())
{
// Don't bother trying to parse the HTTP header.
// Just read something.
SocketChannel
channel
=
(
SocketChannel
)
key
.
channel
();
ByteBuffer
buffer
=
ByteBuffer
.
allocate
(
4096
);
channel
.
read
(
buffer
);
// switch channel to write-only mode
key
.
interestOps
(
SelectionKey
.
OP_WRITE
);
key
.
attach
(
contentBuffer
.
duplicate
());
}
}
catch
(
IOException
ex
)
{
key
.
cancel
();
try
{
key
.
channel
().
close
();
}
catch
(
IOException
cex
)
{}
}
}
}
}
public
static
void
main
(
String
[]
args
)
{
if
(
args
.
length
==
0
)
{
System
.
out
.
println
(
"Usage: java NonblockingSingleFileHTTPServer file port encoding"
);
return
;
}
try
{
// read the single file to serve
String
contentType
=
URLConnection
.
getFileNameMap
().
getContentTypeFor
(
args
[
0
]);
Path
file
=
FileSystems
.
getDefault
().
getPath
(
args
[
0
]);