le()){ ? ? ? ? ? ? ? ? ? ? ? ? ByteBuffer byteBuffer = ByteBuffer.allocate(128);? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? channel.read(byteBuffer); ? ? ? ? ? ? ? ? ? ? ? ? byteBuffer.flip(); ? ? ? ? ? ? ? ? ? ? ? ? CharBuffer charBuffer = CharsetHelper.decode(byteBuffer); ? ? ? ? ? ? ? ? ? ? ? ? String answer = charBuffer.toString(); ? ? ? ? ? ? ? ? ? ? ? ? System.out.println(Thread.currentThread().getId() + "---" + answer); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? String word = getWord(); ? ? ? ? ? ? ? ? ? ? ? ? if(word != null){ ? ? ? ? ? ? ? ? ? ? ? ? ? ? channel.write(CharsetHelper.encode(CharBuffer.wrap(word))); ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? else{ ? ? ? ? ? ? ? ? ? ? ? ? ? ? isOver = true; ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? sleep();? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? }? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? } catch (IOException e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? ? ? finally{ ? ? ? ? ? ? if(channel != null){ ? ? ? ? ? ? ? ? try { ? ? ? ? ? ? ? ? ? ? channel.close(); ? ? ? ? ? ? ? ? } catch (IOException e) {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? if(selector != null){ ? ? ? ? ? ? ? ? try { ? ? ? ? ? ? ? ? ? ? selector.close(); ? ? ? ? ? ? ? ? } catch (IOException e) { ? ? ? ? ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } ? ? } ? ? ? private void init() { ? ? ? ? words = new ArrayBlockingQueue(5); ? ? ? ? try { ? ? ? ? ? ? words.put("hi"); ? ? ? ? ? ? words.put("who"); ? ? ? ? ? ? words.put("what"); ? ? ? ? ? ? words.put("where"); ? ? ? ? ? ? words.put("bye"); ? ? ? ? } catch (InterruptedException e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? }? ? ? ? ? ? ? ? ? random = new Random(); ? ? } ? ? ? ? private String getWord(){ ? ? ? ? return words.poll(); ? ? } ? ? ? private void sleep() { ? ? ? ? try { ? ? ? ? ? ? TimeUnit.SECONDS.sleep(random.nextInt(3)); ? ? ? ? } catch (InterruptedException e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? }? ? ? ? ? private void sleep(long l) { ? ? ? ? try { ? ? ? ? ? ? TimeUnit.SECONDS.sleep(l); ? ? ? ? } catch (InterruptedException e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? } }
|