count = 0;
s = new Socket[5];
while(count <= 4){
new Thread(new Runnable(){
public void run(){
try{
int temp = count;
if(temp<=4)
s[temp] = new Socket(host,1111);
PrintWriter out = new PrintWriter(s[temp].getOutputStream(),true);
out.println(temp);
BufferedInputStream in = new BufferedInputStream(s[temp].getInputStream());
RandomAccessFile raf = new RandomAccessFile(fileName,"rw");
//raf.setLength(fileSize); byte[] buf = new byte[1024];
int i;
raf.seek((fileSize*temp/5-1)==-1 ? 0 : fileSize*temp/5-1);
long tmpSize = fileSize/5;
while ((i=in.read(buf))!=-1 && (tmpSize--!=0 || temp==4)){
raf.write(buf,0,i);
}
raf.close();
in.close();
s[temp].close();
System.out.println(temp + " finished");
}
catch(Exception e){
e.printStackTrace();
}
}
}).start();
try{
Thread.sleep(500);
}
catch(Exception e){
e.printStackTrace();
}
count++;
}上面是我在一个方法里定义的代码,想让它实现的目的是,创建5个与服务端的连接,用多线程读取来自服务端的数据并写到文件里。前四个线程都很正常,会在run方法的最后执行System.out.println(temp + " finished");这一句,但第五个线程不知道怎么搞的,运行时老是会出现一个java.net.SocketException: Connection reset。报错是在这一句:while ((i=in.read(buf))!=-1 && (tmpSize--!=0 || temp==4))
也就是说i = in.read(buf) != -1 ,但是我前几个线程都很正常啊为什么在这里会出现异常呢?
s = new Socket[5];
while(count <= 4){
new Thread(new Runnable(){
public void run(){
try{
int temp = count;
if(temp<=4)
s[temp] = new Socket(host,1111);
PrintWriter out = new PrintWriter(s[temp].getOutputStream(),true);
out.println(temp);
BufferedInputStream in = new BufferedInputStream(s[temp].getInputStream());
RandomAccessFile raf = new RandomAccessFile(fileName,"rw");
//raf.setLength(fileSize); byte[] buf = new byte[1024];
int i;
raf.seek((fileSize*temp/5-1)==-1 ? 0 : fileSize*temp/5-1);
long tmpSize = fileSize/5;
while ((i=in.read(buf))!=-1 && (tmpSize--!=0 || temp==4)){
raf.write(buf,0,i);
}
raf.close();
in.close();
s[temp].close();
System.out.println(temp + " finished");
}
catch(Exception e){
e.printStackTrace();
}
}
}).start();
try{
Thread.sleep(500);
}
catch(Exception e){
e.printStackTrace();
}
count++;
}上面是我在一个方法里定义的代码,想让它实现的目的是,创建5个与服务端的连接,用多线程读取来自服务端的数据并写到文件里。前四个线程都很正常,会在run方法的最后执行System.out.println(temp + " finished");这一句,但第五个线程不知道怎么搞的,运行时老是会出现一个java.net.SocketException: Connection reset。报错是在这一句:while ((i=in.read(buf))!=-1 && (tmpSize--!=0 || temp==4))
也就是说i = in.read(buf) != -1 ,但是我前几个线程都很正常啊为什么在这里会出现异常呢?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货