当前位置:网站首页>NiO uses writable events to handle the situation of one-time write incompleteness
NiO uses writable events to handle the situation of one-time write incompleteness
2022-06-22 16:28:00 【The force is with you】
Server side
public static void main(String[] args) throws IOException {
// Create a server socket
ServerSocketChannel ssc = ServerSocketChannel.open();
// Set asynchronous io
ssc.configureBlocking(false);
// Create selector
Selector selector = Selector.open();
// socket Add to selector , Focus on accept event
ssc.register(selector, SelectionKey.OP_ACCEPT);
// socket Binding port
ssc.bind(new InetSocketAddress(8888));
while (true){
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
iterator.remove();
if(key.isAcceptable()){
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
SelectionKey scKey = sc.register(selector, 0, null);
scKey.interestOps(SelectionKey.OP_READ);
StringBuilder sb = new StringBuilder();
for(int i=0;i<30000000;i++){
sb.append("a");
}
ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
int write = sc.write(buffer);
System.out.println(write);
if(buffer.hasRemaining()){
scKey.interestOps(scKey.interestOps()+SelectionKey.OP_WRITE);
scKey.attach(buffer);
}
}else if(key.isWritable()){
ByteBuffer buffer = (ByteBuffer) key.attachment();
SocketChannel sc = (SocketChannel)key.channel();
int write = sc.write(buffer);
System.out.println(write);
if(!buffer.hasRemaining()){
key.attach(null);
key.interestOps(key.interestOps()-SelectionKey.OP_WRITE);// No longer pay attention to writable events
}
}
}
}
}
client
public static void main(String[] args) throws IOException {
SocketChannel sc = SocketChannel.open();
sc.connect(new InetSocketAddress("localhost",8888));
// receive data
int count = 0;
while (true){
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
count += sc.read(buffer);
System.out.println(count);
buffer.clear();
}
}
边栏推荐
猜你喜欢
随机推荐
Machine learning notes - Hagrid - Introduction to gesture recognition image data set
5.文件的读写(学生类)
SAP ABAP data types, operators and editors-02
在JFlash中添加未知类型的单片机
User exit and customer exit in SAP ABAP -015
SAP ABAP dialog programming tutorial: module pool in -09
【山大会议】WebRTC基础之用户媒体的获取
ALV report in SAP tutorial - ABAP list viewer -012
Unity game optimization (version 2) learning record 8
CMake教程系列-00-简介
odoo部署到服务器并配置为服务
让pycharm项目里面的文本模板支持jinjia2语法
The odoo system sets priorities for the views independently developed by the original model
3. abstract class (shape)
SAP ABAP 内部表:创建、读取、填充、复制和删除-06
Static assertion static_ assert
使用stream api替代sql
What is SAP ABAP? Type, ABAP full form and meaning
【小程序项目开发-- 京东商城】uni-app开发之配置tabBar & 窗口样式
知识管理在业务中的价值如何体现









