Java Reference
In-Depth Information
logger
.
log
(
Level
.
SEVERE
,
"Could not start server"
,
ex
);
}
}
private
class
HTTPHandler
implements
Callable
<
Void
>
{
private
final
Socket
connection
;
HTTPHandler
(
Socket
connection
)
{
this
.
connection
=
connection
;
}
@Override
public
Void
call
()
throws
IOException
{
try
{
OutputStream
out
=
new
BufferedOutputStream
(
connection
.
getOutputStream
()
);
InputStream
in
=
new
BufferedInputStream
(
connection
.
getInputStream
()
);
// read the first line only; that's all we need
StringBuilder
request
=
new
StringBuilder
(
80
);
while
(
true
)
{
int
c
=
in
.
read
();
if
(
c
==
'\r'
||
c
==
'\n'
||
c
==
-
1
)
break
;
request
.
append
((
char
)
c
);
}
// If this is HTTP/1.0 or later send a MIME header
if
(
request
.
toString
().
indexOf
(
"HTTP/"
)
!=
-
1
)
{
out
.
write
(
header
);
}
out
.
write
(
content
);
out
.
flush
();
}
catch
(
IOException
ex
)
{
logger
.
log
(
Level
.
WARNING
,
"Error writing to client"
,
ex
);
}
finally
{
connection
.
close
();
}
return
null
;
}
}
public
static
void
main
(
String
[]
args
)
{
// set the port to listen on
int
port
;
try
{
port
=
Integer
.
parseInt
(
args
[
1
]);
if
(
port
<
1
||
port
>
65535
)
port
=
80
;
}
catch
(
RuntimeException
ex
)
{
port
=
80
;
}