我刚接触 socket  找了本书,练习了一下,现在有几点不明白
网上一些例子写的都是长连接,客户端都是连接了一次,如果在连接期间,服务端关闭,怎么样让客户端定时每隔几秒连一次,直到服务端再打开?
我参考的客户端代码如下
import java.net.*;
import java.nio.channels.*;
import java.nio.*;
import java.io.*;
import java.nio.charset.*;
import java.util.*;public class SocketClient {
  private static SocketChannel socketChannel = null;
  private int serverPort = 10000;
  private ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
  private ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
  private Charset charset = Charset.forName("UTF-8");
  private Selector selector;
  private static boolean flag;  public SocketClient() throws IOException {
      socketChannel = SocketChannel.open();
      InetAddress ia = InetAddress.getLocalHost();
      InetSocketAddress isa = new InetSocketAddress(ia, serverPort);
      try {
          flag = socketChannel.connect(isa);
          socketChannel.configureBlocking(false);
          System.out.println("与服务器的连接建立成功");
          selector = Selector.open();
      } catch (SocketException ex) {
          System.out.println("connect error");
          return;
      }
  }
  public static void main(String args[]) throws IOException {
    final SocketClient client = new SocketClient();
    flag = socketChannel.isConnected();
    if(flag){
        Thread receiver = new Thread() {
            public void run() {
                client.receiveFromUser();
            }
        };        receiver.start();
        client.talk();
    }else{
        //重新连
--------------此段很模糊 自己乱加的--------
        Thread receiver2 = new Thread() {
           public void run() {
            try {
                client.reConnect(flag);
            } catch (IOException ex) {
            }
           }
       };
       receiver2.start();
---------------------------------------
    }
  }
  
  //重新连接
 public static void reConnect(boolean flag) throws IOException {
     while(!flag){
//         timer.schedule(new TimerTask() {
//          public void run() {
//            start();
//            timer.cancel();
//          }
//          public void start() {
//            try {
                new SocketClient();
//            } catch (IOException ex) {
//            }
//          }
//        }, 6000, 6000);     
           flag = socketChannel.isConnected();
       }
------------连是连上了,可是得建立talk,还得用线程,可是线程里的对象一定是final的,所以等于连了两次----
       if (flag) {
           final SocketClient client2 = new SocketClient();
           Thread receiver = new Thread() {
               public void run() {
                   client2.receiveFromUser();
               }
           };
           receiver.start();
           client2.talk();
       }
------------------------------------------------
 }  public void receiveFromUser() {
    try {
      BufferedReader localReader = new BufferedReader(new InputStreamReader(
          System.in));
      String msg = null;
      while ( (msg = localReader.readLine()) != null) {
          if ( msg.length() < 1) {
              System.out.println("null");
              msg = "syn";
          }        synchronized (sendBuffer) {
          sendBuffer.put(encode(msg + "\r\n"));
        }        if (msg.equals("echo:bye")) {
          System.out.println("关闭");
          break;
        }
        if (msg.equals("bye")) {
          System.out.println("关闭");
          break;
        }
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }  public void talk() throws IOException {
    socketChannel.register(selector,
                           SelectionKey.OP_READ |
                           SelectionKey.OP_WRITE);
    while (selector.select() > 0) {
      Set readyKeys = selector.selectedKeys();
      Iterator it = readyKeys.iterator();
      while (it.hasNext()) {
        SelectionKey key = null;
        try {
          key = (SelectionKey) it.next();
          it.remove();          if (key.isReadable()) {
            receive(key);
          }
          if (key.isWritable()) {
            send(key);
          }        }
        catch (IOException e) {
//          e.printStackTrace();
            System.out.println("服务端已关闭");
          try {
            if (key != null) {
              key.cancel();
              key.channel().close();
            }
          }
          catch (Exception ex) {
            e.printStackTrace();
          }
-------------------服务端端开,重新连,也存在二次连接的问题----------
          //重新连
          reConnect(false);  
-----------------------------------------------------------------
        }
        try {
          Thread.sleep(1);
        }
        catch (InterruptedException ex1) {
        }
      } //#while
      try {
        Thread.sleep(5);
      }
      catch (InterruptedException ex2) {
      }
    } //#while
  }
  
 
  public void send(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    synchronized (sendBuffer) {
      sendBuffer.flip(); //把极限设为位置
      socketChannel.write(sendBuffer);
      sendBuffer.compact();
    }
  }  public void receive(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    socketChannel.read(receiveBuffer);
    receiveBuffer.flip();
    String receiveData = decode(receiveBuffer);    if (receiveData.indexOf("\n") == -1) {
      return;
    }
//    System.out.println(receiveData);
    String outputData = receiveData.substring(0, receiveData.lastIndexOf("\n") + 1);
    System.out.print(outputData);
    if (outputData.equals("bye\r\n")) {
      key.cancel();
      socketChannel.close();
      System.out.println("关闭与服务器的连接");
      selector.close();
      System.exit(0);
    }    ByteBuffer temp = encode(outputData);
    receiveBuffer.position(temp.limit());
    receiveBuffer.compact();
  }  public String decode(ByteBuffer buffer) { //解码
    CharBuffer charBuffer = charset.decode(buffer);
    return charBuffer.toString();
  }  public ByteBuffer encode(String str) { //编码
    return charset.encode(str);
  }
  private java.util.Timer timer = new java.util.Timer();
}
请帮帮我

解决方案 »

  1.   


    你new   SocketClient(); 
    两次也就重连了2次
      

  2.   

    代码太长,我就不仔细看了!我提供一个思路吧!while(true){ // 最外面的循环,保证不会退出
      try{
        // 连接服务器
        // 其它的代码
      }catch(Exception ex){
        // 如果发生异常,则休眠一段时间
        try{
          Thread.sleep(1000);
        }catch(Exception ee){}
      }
    }
      

  3.   

    我知道构造了两次,因为第二次我是得用到线程里 进行talk啊,第一次是连上了,但是其对象用不上啊