我现在在开发一个关于socket的客户端,碰到了如下的一些问题.
目前我的目标是开发一个客户端,在打开一个socket的情况下,连续向服务器发送和接受信息!(比如先发送一个认证信息,服务器返回认证成功信息,接着我在向服务器发送具体内容,服务器会给我返回一个处理信息的一个简单模型).
代码如下:
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();
  .......
}