socket.configureBlocking(false);
socket.socket().bind(new InetSocketAdress("127.0.0.1", 8000);
selector = Selector.open();
socket.register(selector, SelectionKey.OP_ACCEPT);
while(true) {
if(selector.select()==0) continue;
Set
Iterator
while(key.hasNext()) {
SelectionKey key = (SelectionKey) key.next();
keys.remove();
// accept connection
if(key.isAcceptible()) {
// get SocketChannel from key
SocketChannel channel = server.accept();
channel.configureBlocking(false);
// enable read write to channel
channel.register(selector, SelectionKey.OP_READ |
SelectionKey.OP_WRITE);
}
// accept readable package
if(key.isReadable()) {
// get SocketChannel from key
SocketChannel channel = (SocketChannel)
key.channel();
if(channel.isConnectionPending())
channel.finishConnect();
int read = 0;
Charset charset =
Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charbuffer = null;
ByteBuffer buffer = ByteBuffer.allocate(1024);
ByteArrayOutputStream stream =
new ByteArrayOutputStream();
while((read = target.read(buffer)) > 0) {
stream.write(buffer.array(), 0, read);
buffer.clear();
}
charbuffer = decoder.decode(
ByteBuffer.wrap(stream.toByteArray()));
stream.close();
return charbuffer;
}
// write to channel
if(key.isWriteable()) {
// get SocketChannel from key
SocketChannel channel =
(SocketChannel) key.channel();
channel.write(ByteBuffer.wrap(
new String("hello from server").getBytes()));
}
}
}
No comments:
Post a Comment