Java Reference
In-Depth Information
key
.
channel
().
close
();
}
catch
(
IOException
cex
)
{
// ignore
}
}
Example 11-2
puts this all together in a complete chargen server that processes multiple
connections efficiently in a single thread.
Example 11-2. A nonblocking chargen server
import
java.nio.*
;
import
java.nio.channels.*
;
import
java.net.*
;
import
java.util.*
;
import
java.io.IOException
;
public
class
ChargenServer
{
public
static
int
DEFAULT_PORT
=
19
;
public
static
void
main
(
String
[]
args
)
{
int
port
;
try
{
port
=
Integer
.
parseInt
(
args
[
0
]);
}
catch
(
RuntimeException
ex
)
{
port
=
DEFAULT_PORT
;
}
System
.
out
.
println
(
"Listening for connections on port "
+
port
);
byte
[]
rotation
=
new
byte
[
95
*
2
];
for
(
byte
i
=
' '
;
i
<=
'~'
;
i
++)
{
rotation
[
i
-
' '
]
=
i
;
rotation
[
i
+
95
-
' '
]
=
i
;
}
ServerSocketChannel
serverChannel
;
Selector
selector
;
try
{
serverChannel
=
ServerSocketChannel
.
open
();
ServerSocket
ss
=
serverChannel
.
socket
();
InetSocketAddress
address
=
new
InetSocketAddress
(
port
);
ss
.
bind
(
address
);
serverChannel
.
configureBlocking
(
false
);
selector
=
Selector
.
open
();
serverChannel
.
register
(
selector
,
SelectionKey
.
OP_ACCEPT
);
}
catch
(
IOException
ex
)
{
ex
.
printStackTrace
();
return
;
}
while
(
true
)
{