Created
December 7, 2014 08:37
-
-
Save takei-shg/8cf62c9ecca621cba4d7 to your computer and use it in GitHub Desktop.
java NIO echo server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.net.InetSocketAddress; | |
import java.nio.ByteBuffer; | |
import java.nio.channels.SelectionKey; | |
import java.nio.channels.Selector; | |
import java.nio.channels.ServerSocketChannel; | |
import java.nio.channels.SocketChannel; | |
import java.nio.charset.Charset; | |
import java.util.Iterator; | |
/** | |
* Created by nanika on 2014/12/07. | |
*/ | |
public class NIOServer { | |
int port = 9999; | |
private Selector selector; | |
public void start() throws IOException { | |
System.out.println("NIOServer start"); | |
selector = Selector.open(); | |
ServerSocketChannel serverChannel = ServerSocketChannel.open(); | |
serverChannel.configureBlocking(false); | |
serverChannel.socket().bind(new InetSocketAddress(port)); | |
serverChannel.register(selector, SelectionKey.OP_ACCEPT); | |
while (selector.select() > 0) { | |
for (Iterator it = selector.selectedKeys().iterator(); it.hasNext();) { | |
SelectionKey key = (SelectionKey) it.next(); | |
it.remove(); | |
if (key.isAcceptable()) { | |
doAccept((ServerSocketChannel) key.channel()); | |
} else if (key.isReadable()) { | |
doRead((SocketChannel) key.channel()); | |
} | |
} | |
} | |
serverChannel.close(); | |
} | |
private void doAccept(ServerSocketChannel serverChannel) throws IOException { | |
System.out.println("doAccept"); | |
SocketChannel channel = serverChannel.accept(); | |
channel.configureBlocking(false); | |
channel.register(selector, SelectionKey.OP_READ); | |
} | |
private void doRead(SocketChannel socketChannel) throws IOException { | |
System.out.println("doRead"); | |
ByteBuffer buf = ByteBuffer.allocate(32); | |
Charset cset = Charset.forName("UTF-8"); | |
if (socketChannel.read(buf) < 0) { | |
return; | |
} | |
buf.flip(); | |
cset.decode(buf); | |
buf.flip(); | |
socketChannel.write(buf); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment