实验三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();

}

}

}

猜你喜欢

转载自frankytony.iteye.com/blog/2284559
NIO
今日推荐