首页 > Linux操作系统 > Linux操作系统 > Java中的异步网络编程(转)
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 piky2004@126.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();
}
}
在以上程序中,也可以为外部应用提供一个回调函数,以便在网络异常或恢复正常时通知应用。服务应用的网络通信类类似,可以放在同一类中。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10294527/viewspace-122481/ ,如需转载,请注明出处,否则将追究法律责任。