java nio server_java nio server demo jdk1.8

import java.io.IOException;

import java.net.InetSocketAddress;

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.nio.charset.Charset;

import java.util.Iterator;

import java.util.Set;public classEchoServer {public staticSelectorLoop connectionBell;public staticSelectorLoop readBell;public boolean isReadBellRunning=false;public static voidmain(String[] args) throws IOException {newEchoServer().startServer();

}public voidstartServer() throws IOException {

connectionBell= newSelectorLoop();

readBell= newSelectorLoop();

ServerSocketChannel ssc=ServerSocketChannel.open();

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

ssc.configureBlocking(false);

ssc.register(connectionBell.getSelector(), SelectionKey.OP_ACCEPT);newThread(connectionBell).start();

}public classSelectorLoop implements Runnable {privateSelector selector;private ByteBuffer temp = ByteBuffer.allocate(1024);publicSelectorLoop() throws IOException {this.selector =Selector.open();

}publicSelector getSelector() {return this.selector;

}public voidrun() {while(true) {try{this.selector.select();

Set selectKeys = this.selector.selectedKeys();

Iterator it =selectKeys.iterator();while(it.hasNext()) {

SelectionKey key=it.next();

it.remove();this.dispatch(key);

}

}catch(IOException e) {

e.printStackTrace();

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}public voiddispatch(SelectionKey key) throws IOException, InterruptedException {if(key.isAcceptable()) {

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

SocketChannel sc=ssc.accept();

sc.configureBlocking(false);

sc.register(readBell.getSelector(), SelectionKey.OP_READ);

synchronized(EchoServer.this) {if (!EchoServer.this.isReadBellRunning) {

EchoServer.this.isReadBellRunning = true;newThread(readBell).start();

}

}

}else if(key.isReadable()) {

SocketChannel sc=(SocketChannel) key.channel();int count =sc.read(temp);if (count < 0) {

key.cancel();

sc.close();return;

}

temp.flip();

String msg= Charset.forName("UTF-8").decode(temp).toString();

System.out.println("Server received ["+msg+"] from client address:" +sc.socket());//Thread.sleep(1000);

sc.write(ByteBuffer.wrap(msg.getBytes(Charset.forName("UTF-8"))));

temp.clear();

}

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值