日期:2014-05-20  浏览次数:20750 次

java非阻塞通信的问题,高手请解答
最近学习非阻塞通信的知识,有点一知半解,下面的例子是参考 孙卫琴 <<java网络编程精讲>>的
高手给看看

客户端代码:
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.nio.charset.*;

public class NonBlockingClient {

   private SocketChannel socketChannel=null;
   
   private ByteBuffer sendBuffer=ByteBuffer.allocate(1024);      // 发送缓冲区用于向服务器发送数据
   private ByteBuffer receiveBuffer=ByteBuffer.allocate(1024); //接收缓冲区用于从服务器端接收数据

   private Charset charset=Charset.forName("GBK");
   private Selector selector;
   
   public NonBlockingClient() throws IOException
   {
     socketChannel=SocketChannel.open();  //创建SocketChannel对象
     InetAddress ia=InetAddress.getLocalHost();
     InetSocketAddress isa=new InetSocketAddress(ia,10000);
     socketChannel.connect(isa);   //采用阻塞模式连接服务器
     socketChannel.configureBlocking(false); //采用非阻塞模式接收和发送数据
     System.out.println("与服务器连接成功");
     selector=Selector.open(); //创建监听器
   }
   
   public void receiveData() //从控制台接收数据到缓冲区
   {
       try{
       
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      String msg=null;
      while((msg=br.readLine())!=null)
      {
  if(msg.equals("exit"))
             break;
        synchronized(sendBuffer) //同步代码块,sendBuffer为共享资源
        {
         sendBuffer.put(encode(msg+"\r\n"));
        }
        
      }
       }
       catch(IOException e)
       {
         e.printStackTrace();
       }
   }
    
   public void communicate() throws IOException
   {
     socketChannel.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE);
     while(selector.select()>0) //采用阻塞方式,返回相关事件已经发生的SelectionKey对象的数目
     {
      Set readyKeys=selector.selectedKeys(); //返回相关事件已经发生的SelectionKey对象的集合
      Iterator it=readyKeys.iterator();
      while(it.hasNext())
      {
         SelectionKey key=null;
         try
         {
           key=(SelectionKey)it.next();
           it.remove();
           
           if(key.isReadable())