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();
}
}
在以上程序中,也可以为外部应用提供一个回调函数,以便在网络异常或恢复正常时通知应用。服务应用的网络通信类类似,可以放在同一类中。
本文地址:http://com.8s8s.com/it/it11301.htm