日期:2014-05-20 浏览次数:20863 次
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
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.LinkedList;
import java.util.List;
/*该类用于接收响应的数据,并传送到访问终端*/
class MyThread extends Thread{
private Selector stor;
private SocketChannel sc;
private List <SocketChannel> waitReg = new LinkedList <SocketChannel>();
public MyThread() {
//创建一个信号监视器
try {
stor = Selector.open();
} catch (IOException e) {
e.printStackTrace();
}
}
public void register(SocketChannel dc,SocketChannel sc){
this.sc = sc;
waitReg.add(dc);
stor.wakeup();
}
public void run(){
while(true){
//会阻塞,直到有事件触发,返回事件数目
int count = 0;
try {
count = stor.select();
} catch (IOException e) {
e.printStackTrace();
}
//注册
while(waitReg.size() > 0){
try {
SocketChannel sc = waitReg.get(0);
waitReg.remove(sc);
sc.configureBlocking(false);
sc.register(stor,SelectionKey.OP_READ);
} catch (Exception e) {
e.printStackTrace();
}
}
if(count == 0){
System.out.println("没有发生任何事件");
continue;
}
//遍历所有已触发的事件,进行处理
Iterator it = stor.selectedKeys().iterator();
while(it.hasNext()){
SelectionKey sky = (SelectionKey)it.next();
//将该事件处理完后则删除
it.remove();
if(sky.isReadable()){
System.out.println("接收应用服务器结果");
ByteBuffer bb = ByteBuffer.allocate(10240);
SocketChannel stc =(SocketChannel)sky.channel();
try{
int len = stc.read(bb);
bb.flip();
sc.write(bb);
if(len == -1){
sky.cancel();
}
}catch (IOException e){
sky.cancel();
e.printStackTrace();
continue;
}
}
}
}
}
}
public class Test {
public void run(){
//创建一个信号监视器
Selector stor = null;
try {
stor = Selector.open();
} catch (IOException e) {
e.printStackTrace();
return;
}
//创建一个监听
ServerSocketChannel sc = null;
try {
sc = ServerSocketChannel.open();
//设监听为异步
sc.configureBlocking(false);
} catch (IOException e) {
e.printStackTrace();
return;
}
//绑定监听的端口
try {
sc.socket().bind(new InetSocketAddress(9001));
} catch (IOException e) {
e.printStackTrace();
return;
}
//将监听的OP_ACCEPT类型注册到stor信号监视器
try {
sc.register(stor,SelectionKey.OP_ACCEPT);
} catch (ClosedChannelException e) {
e.printStackTrace();
return;
}
MyThread mt = new MyThread();
mt.start();
//开始循环等待监听事件触发
while(true){
//会阻塞,直到有事件触发,返回事件数目
int count = 0;
try {
count = stor.select();
} catch (IOException e) {
e.printStackTrace();
continue;
}
if(count < 0){