import java.io.*; import java.net.*; import java.awt.event.*; 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; }</td> </tr> <tr> <td height="20" colspan="2">
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 ghf@china.com"); 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(); } } 在以上程序中,也可以为外部应用提供一个回调函数,以便在网络异常或恢复正常时通知应用。</td> </tr> </table> </td> </tr> <tr>
服务应用的网络通信类类似,可以放在同一类中。
↑返回目录
前一篇: GIF解码和编码操作库源码
后一篇: 找吸血鬼数