该文章对编写客户服务器应用的java程序员有所帮助,可以解决程序在对方出现故障的时候继续稳定运行.   目前java平台已经广泛应用于各类客户/服务器系统中,在实际编程中,往往需要网络的异步处理。比如客户程序,如果客户程序运行先于服务程序,则客户程序则需要在服务程序启动后再自动连接服务程序;在客户程序运行中如果服务程序中途停止,则也需要在不停止的条件下,等待服务程序运行并重新连接。下面提供了一类异步编程的方法。 网络异步应用涉及到如下几个关键点:    客户应用启动后,检测服务应用是否存在。如果不存在,则等待服务应用启动,同时不堵塞客户应用其他任务的执行。一旦服务应用启动,客户应用应该及时的与其建立连接。    客户应用和服务应用在数据通信中,服务应用异常退出后,客户应用应可以检测到服务应用的退出。同时客户应用自动清除该通信链路,回到初始状态,等待服务应用重新启动。   该网络异步编程首先涉及到一个定时器和定时器事件。该定时器用于不断的检测网络中客户应用和服务应用是否连通,同时在服务应用出现异常时中止数据通信,返回到初始状态。网络的故障可以通过网络方法的异常处理获知。   定时器包含在网络通信类中,使得使用该类的应用感知不到定时器的存在,而方便的处理网络信息。 该客户程序类如下结构:  public class NetComm             implements ActionListener {     javax.swing.Timer timer = new javax.swing.Timer(3000,this);         Socket sock; private EventNotifier en; public static int    net_state = 0; InetAddress ServerAddr; int ServerPort;     public NetComm(InetAddress addr, int port){    ServerAddr = addr;    ServerPort  = port; } 
 
public void NetComm_Init() {             net_state = 1;        try {            sock = new Socket(ServerAddr, ServerPort);        } catch (IOException e) {            net_state = 0;        }        timer.start(); }     public void NetComm_Data() {    try {        OutputStream outputstream = sock.getOutputStream();                BufferedWriter out = new BufferedWriter            (new OutputStreamWriter(outputstream));                    out.write("java by [email protected]");        out.flush();  
       BufferedReader in = new BufferedReader                (new InputStreamReader(sock.getInputStream()));                boolean more = true;        while(more) {            String str = in.readLine();             if(str == null) more = false;            else                // 处理数据                 System.out.println(str);        }                    in.close();  
       } catch (IOException e) {        NetComm_Close();        net_state = 0;        }    timer.start();    }        public void NetComm_Close()    {        if(sock != null)            try{                sock.close();                } catch ( IOException e) {            }    }        public void actionPerformed(ActionEvent e)    {        if(net_state == 0)               NetComm_Init();        else                    NetComm_Data();    } }  
在以上程序中,也可以为外部应用提供一个回调函数,以便在网络异常或恢复正常时通知应用。服务应用的网络通信类类似,可以放在同一类中。  
 
  |