java NIO通信demo
server端
?
public class NIOClient {Selector selector;SocketChannel sc ; public void init(){try {selector = Selector.open();sc = SocketChannel.open();sc.connect(new InetSocketAddress("127.0.0.1",8000));sc.configureBlocking(false);sc.register(selector, SelectionKey.OP_READ);} catch (IOException e) {e.printStackTrace();}}public void send(String str){try {if(sc.isConnected()){sc.write(ByteBuffer.wrap(str.getBytes()));}else{System.out.println("没有连接成功");}} catch (IOException e) {e.printStackTrace();}}public String read(){ByteBuffer bb = ByteBuffer.allocate(4000);try {if(selector.select(1000)==1){Iterator it = selector.selectedKeys().iterator();while(it.hasNext()){String rt = "";SelectionKey k = (SelectionKey)it.next();it.remove();int cnt = 0;if(k.isReadable()){SocketChannel s = (SocketChannel)k.channel();while(s.isOpen()&&(cnt=s.read(bb))>0){rt += new String(bb.array()).trim();bb.clear();}s.close();}close();k.cancel();return rt;}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}public void close(){try {sc.close();selector.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args){NIOClient l = new NIOClient();l.init();l.send("eee");System.out.println(l.read());}}?
?