JAVA socket 怎样暂停这段程序 急求
下面这段是我触发“开始”按钮下载文件时执行的代码
File file = new File(filesavePath);
if(!file.exists()){
System.out.println("文件不存在,创建");
file.createNewFile();}
Socket server = new Socket(serverIP, 8880);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// 通过Socket连接文件服务器
PrintWriter outtosocket = new PrintWriter(server
.getOutputStream());
;
outtosocket.println(downfilemessage);
outtosocket.flush();
InputStream netIn = server.getInputStream();
InputStream in = new DataInputStream(
new BufferedInputStream(netIn));
//创建缓冲区缓冲网络数据
byte[] buf = new byte[20480];
int num = in.read(buf);
while (num != (-1)&&isStop!=true) //isStop(类的一个全局变量)初始化为false
{
raf.write(buf, 0, num);
raf.skipBytes(num);
num = in.read(buf);//继续从网络中读取文件
}
in.close();
raf.close();
server.close();
}
下面是我“暂停”按钮触发事件:
isStop=true;
我想通过“暂停”按钮改变isStop的值从而终止文件的下载,但运行时发现程序不会终止,继续运行知道文件下载完毕,请高手们帮忙看看怎么解决啊
------解决方案--------------------
在 开始 按钮的事件处理函数中,启动一个线程,
大致改成下面:
Java code
Thread downloader=new Thread(){
public void run(){
File file = new File(filesavePath);
if(!file.exists()){
System.out.println("文件不存在,创建");
file.createNewFile();}
Socket server = new Socket(serverIP, 8880);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// 通过Socket连接文件服务器
PrintWriter outtosocket = new PrintWriter(server
.getOutputStream());
;
outtosocket.println(downfilemessage);
outtosocket.flush();
InputStream netIn = server.getInputStream();
InputStream in = new DataInputStream(
new BufferedInputStream(netIn));
// 创建缓冲区缓冲网络数据
byte[] buf = new byte[20480];
int num = in.read(buf);
while (num != (-1)&&isStop!=true) //isStop(类的一个全局变量)初始化为false
{
raf.write(buf, 0, num);
raf.skipBytes(num);
num = in.read(buf);//继续从网络中读取文件
}
in.close();
raf.close();
server.close();
}
};
downloader.start();