实验三5 NIO

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.ServerSocket;

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;

 

public class TestNIOServer {

 

public static void main(String[] args) {

int port = 1019;

 

System.out.println("listening for connections on port "+port);

 

try {

ServerSocketChannel serverSocketChanel = ServerSocketChannel.open();

ServerSocket ss = serverSocketChanel.socket();

ss.bind(new InetSocketAddress(port));

serverSocketChanel.configureBlocking(false);

Selector listener = Selector.open();

serverSocketChanel.register(listener, SelectionKey.OP_ACCEPT);

 

while(true){

//this method is blocking at least one channel is selected, 

int ii = listener.select();

System.out.println(ii);

 

Set<SelectionKey> readyKeys = listener.selectedKeys();

Iterator<SelectionKey> iterator = readyKeys.iterator();

while(iterator.hasNext()){

SelectionKey key = iterator.next();

iterator.remove();

if(key.isAcceptable()){

ServerSocketChannel server = (ServerSocketChannel) key.channel();

SocketChannel client = server.accept();

System.out.println("Accepted connection from "+ client);

client.configureBlocking(false);

SelectionKey key2 = client.register(listener, SelectionKey.OP_WRITE);

ByteBuffer output = ByteBuffer.allocate(4);

output.putInt(0);

output.flip();

key2.attach(output);

}else if(key.isWritable()){

SocketChannel client = (SocketChannel) key.channel();

ByteBuffer output = (ByteBuffer) key.attachment();

if(!output.hasRemaining()){

output.rewind();

int value = output.getInt();

output.clear();

output.putInt(value+1);

output.flip();

}

client.write(output);

}

}

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

 

 

}

 

}

 

 

 

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.IntBuffer;

import java.nio.channels.SocketChannel;

 

public class TestNIOClient {

 

public static void main(String[] args) {

try {

SocketChannel client = SocketChannel.open(new InetSocketAddress("localhost",1019));

ByteBuffer buffer = ByteBuffer.allocate(4);

IntBuffer view = buffer.asIntBuffer();

for(int i=0;i<10;i++){

client.read(buffer);

int actual = view.get();

buffer.clear();

view.rewind();

System.out.println(actual);

}

 

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

}

 

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值