Last active
July 14, 2017 01:04
-
-
Save liweinan/872159a8fc9207b2fe20fec7e22a5588 to your computer and use it in GitHub Desktop.
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
package nio.sandbox; | |
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.util.Iterator; | |
import java.util.Set; | |
/** | |
* Created by weinanli on 14/07/2017. | |
*/ | |
public class SocketReadWrite { | |
private static Selector _selector; | |
private static ByteBuffer _buffer = ByteBuffer.allocateDirect(1024); | |
public static void main(String[] args) throws Exception { | |
_selector = Selector.open(); | |
ServerSocketChannel channel = ServerSocketChannel.open(); | |
channel.socket().bind(new InetSocketAddress(8080)); | |
channel.configureBlocking(false); | |
channel.register(_selector, SelectionKey.OP_ACCEPT); | |
while (!Thread.interrupted()) { | |
_selector.select(); | |
Set keys = _selector.selectedKeys(); | |
Iterator iterator = keys.iterator(); | |
while (iterator.hasNext()) { | |
SelectionKey key = (SelectionKey) (iterator.next()); | |
if (key.isAcceptable()) { | |
acceptRequestAndRegisterReadEvent(key); | |
} | |
if (key.isReadable()) { | |
readRequestAndEcho(key); | |
} | |
iterator.remove(); | |
} | |
} | |
} | |
private static void readRequestAndEcho(SelectionKey key) throws IOException { | |
SocketChannel _channel = (SocketChannel) key.channel(); | |
_buffer.clear(); | |
int count = 0; | |
while ((count = _channel.read(_buffer)) > 0) { | |
_buffer.flip(); | |
while(_buffer.hasRemaining()) { | |
_channel.write(_buffer); // echo | |
} | |
} | |
_buffer.clear(); | |
} | |
private static void acceptRequestAndRegisterReadEvent(SelectionKey key) { | |
ServerSocketChannel channel = (ServerSocketChannel) key.channel(); | |
try { | |
SocketChannel _channel = channel.accept(); | |
_channel.configureBlocking(false); | |
_channel.register(_selector, SelectionKey.OP_READ); | |
_buffer.clear(); | |
_buffer.put("Hi!\r\n".getBytes()); | |
_buffer.flip(); | |
_channel.write(_buffer); | |
} catch (IOException e) { | |
// nothing to do | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment