import com.google.common.base.Charsets;
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;
class Scratch {
public static void main(String[] args) {
try {
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.bind(new InetSocketAddress("0.0.0.0", 8888));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
try {
if (selector.select() > 0) {
Set<SelectionKey> keySet = selector.selectedKeys();
Iterator<SelectionKey> iterator = keySet.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
iterator.remove();
if (selectionKey.isValid()) {
if (selectionKey.isAcceptable()) {
ServerSocketChannel serverSocketChannel1 = ((ServerSocketChannel) selectionKey.channel());
SocketChannel socketChannel = serverSocketChannel1.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ)
//附加连接属性对象
.attach(ByteBuffer.allocate(1024));
}
if (selectionKey.isReadable()) {
lineBasedLimiterCodec(selectionKey);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
static void lineBasedLimiterCodec(SelectionKey selectionKey) throws Exception {
ByteBuffer dataBuf = ((ByteBuffer) selectionKey.attachment());
SocketChannel socketChannel = ((SocketChannel) selectionKey.channel());
ByteBuffer byteBuffer = ByteBuffer.allocate(1);
int length = socketChannel.read(byteBuffer);
//连接断开
if (length < 0) {
socketChannel.close();
} else {
byte[] data = new byte[length];
byteBuffer.flip();
byteBuffer.get(data);
int char_ = data[0];
//监听回车符
if (char_ != '\r') {
dataBuf.put(data);
} else {
int realLength = dataBuf.position();
byte[] data_ = new byte[realLength];
dataBuf.flip();
//去掉换行符
if (dataBuf.get() == '\n') {
dataBuf.position(1);
data_ = new byte[realLength - 1];
} else {
dataBuf.position(0);
}
dataBuf.get(data_);
String resp = new String(data_, Charsets.UTF_8);
System.err.println("read msg=" + resp);
socketChannel.write(ByteBuffer.wrap("hello client\r\n".getBytes()));
dataBuf.clear();
}
}
}
}
java手写解析换行符的NIO服务端
猜你喜欢
转载自blog.csdn.net/lmx1989219/article/details/98083234
今日推荐
周排行