java <select >_java select单线程 服务器

*

*/importjava.io.IOException;importjava.net.InetSocketAddress;importjava.nio.ByteBuffer;importjava.nio.channels.ClosedChannelException;importjava.nio.channels.SelectableChannel;importjava.nio.channels.SelectionKey;importjava.nio.channels.Selector;importjava.nio.channels.ServerSocketChannel;importjava.nio.channels.SocketChannel;importjava.util.HashMap;importjava.util.Iterator;importjava.util.Map;importjava.util.Set;public classMyselect {private Map map = new HashMap();public static voidmain(String[] args) {//TODO Auto-generated method stubnewMyselect().initsocket();}public voidinitsocket(){

ServerSocketChannel ssc=null;

Selector selector=null;

Iterator iter=null;try{

ssc=ServerSocketChannel.open();

ssc.socket().setReuseAddress(true);

ssc.socket().bind(new InetSocketAddress(8081));

selector=Selector.open();

ssc.configureBlocking(false);

ssc.register(selector, SelectionKey.OP_ACCEPT);

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}while (true) {try{int keys = selector.select(1000);if (keys <= 0)continue;

iter=null;

Set set_key =selector.selectedKeys();

iter=set_key.iterator();

}catch(Exception e) {//TODO: handle exception

}while(iter.hasNext()) {

SelectionKey key=iter.next();

iter.remove();if(key.isAcceptable()) {try{

SocketChannel client=ssc.accept();

client.configureBlocking(false);

client.register(selector, SelectionKey.OP_READ);

}catch(ClosedChannelException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}else if(key.isReadable()) {

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

ByteBuffer dst= ByteBuffer.allocate(4094);

StringBuffer sb= newStringBuffer();int readsize = -1;try{while ((readsize = client.read(dst)) > 0) {

dst.flip();

sb.append(new String(dst.array(), 0, readsize));

dst.clear();if (readsize < 0) {//对端关闭,read 返回-1,没有数据返回0,如果客户端一直没有发送数据则isReadable事件激发不了。

System.out.println("client "

+((InetSocketAddress) client.getRemoteAddress()).getAddress().getHostAddress()+ " is closed");

key.cancel();//取消select 监听并关闭服务端socket.

client.close();continue;

}

map.put(client, sb.toString());//

System.out.println("server read : "+sb.toString());

client.register(selector, SelectionKey.OP_WRITE);

}

}catch(Exception e) {//TODO: handle exception

}

}else if(key.isWritable()) {

System.out.println("coming write\n");

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

String req=map.get(client);if(req==null) {continue;

}

System.out.println("ready write len"+req.length());

String httpResponse= "HTTP/1.1 200 OK\r\n" +

"Content-Length: "+req.length()+"\r\n" +

"Content-Type: text/html\r\n" +

"\r\n" +req;//int wcode=client.write(ByteBuffer.wrap(httpResponse.getBytes()));

try{//捕捉异常,客户端端可能关闭导致写异常。int wcode=client.write(ByteBuffer.wrap(req.getBytes()));

System.out.println("write code "+wcode);

client.register(selector, SelectionKey.OP_READ);

}catch(Exception e) {//TODO: handle exception

map.remove(client);//关闭服务器端socket,并取消监听

key.cancel();

System.out.println("client is closed!");try{

client.close();

}catch(IOException e1) {//TODO Auto-generated catch block

e1.printStackTrace();

}

}

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值