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

java socket 简单问题
我刚接触 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) {