刚才太乱,重新整理一下:
void ConnectServer() throws IOException
{
  bf = ByteBuffer.allocateDirect(1024);
  InetSocketAddress ad = new InetSocketAddress(this.servername,this.serverport);

  this.clientsocketchannel = SocketChannel.open(); //设置socket管道
  this.clientsocketchannel.configureBlocking(false);
  this.clientsocketchannel.connect(ad);  this.slt = Selector.open();
  this.clientsocketchannel.register (this.slt,SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE);
}  //发送数据
  private void SendMessage(byte[] SendMessage)throws IOException
  {
    while (this.slt.select() > 0)//出错
    {
      Set readykey = slt.selectedKeys();
      Iterator readyitor = readykey.iterator();      while (readyitor.hasNext())
      {
        SelectionKey skey = (SelectionKey) readyitor.next();
        readyitor.remove();        if (skey.isWritable())
        {
          SocketChannel keychannel = (SocketChannel) skey.channel();
          keychannel.write(ByteBuffer.wrap(this.sendmessage));
        }
       }//end while
     }//end while     
  }//接受数据
private void GetEchoMessage()throws IOException
{
  while(this.slt.select(500) > 0)//出错
  {
    Set readykey = slt.selectedKeys();
    Iterator readyitor = readykey.iterator();    while (readyitor.hasNext())
    {
      SelectionKey skey = (SelectionKey) readyitor.next();
      readyitor.remove();      if (skey.isWritable())
      {
        SocketChannel keychannel = (SocketChannel) skey.channel();
        keychannel.read(bf);
       }
     }
   }
}public static void main(String[] arg)
{
  ......
  connectserver(..);
  SendMessage(...);
  GetEchoMessage();
  .......
  SendMessage(...);
  GetEchoMessage();
  .......
}

解决方案 »

  1.   

    我觉得第一次SendMessage的时候,恐怕就在也出不了while (this.slt.select() > 0)循环了,因为select()方法如果没有就绪的通道,就会一直阻塞,直到就绪。后果就是一直向服务器发信息。
      

  2.   

    为什么没有就绪的通道呢?this..register (this.slt,SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE);
    这一句里我将clientsocketchannel注册进去,selector应该有一个可以就绪的通道了啊?
    实际测试的时候this.slt.select() = 0
      

  3.   

    是不是没连上SERVER!
    还是不要用SELECTOR啦,直接用阻塞模式,一发一收比较好
      

  4.   

    你这不是客户端吗,根服务器没什么关系。
    就象传统的JAVA SOCKET,先发信息,发完后一直等着接收,
    全部接收完,再发信息,然后再收...
    你的客户端应该不是多线程吧