public class UpLoadThread implements Runnable{
private Socket s;
private int count=1;//此处把count改成成员变量用于线程共享记录重名文件数
/*UpLoadThread(Socket s){
this.s = s;
} */
public void setSocket(Socket s){//在服务器端辅助UpLoadThread对象共享的工具方法
this.s = s;
}
public void run(){
String ip = s.getInetAddress().getHostAddress();
try{
System.out.println(ip+"::::connect");
InputStream ips = s.getInputStream();
File file = new File(ip+"("+(count)+")"+".txt");
while(file.exists()){//此处改为while,可保证即使你服务器重启,依然可以确保文件名称编排连续
file = new File(ip+"("+(++count)+")"+".txt");//count++改为++count
}
FileOutputStream fos = new FileOutputStream(file);
byte[] arr = new byte[1024];
int len = 0;
while((len = ips.read(arr))!=-1){
fos.write( arr,0,len);
}
OutputStream ops = s.getOutputStream();
ops.write("文件上传成功".getBytes());
fos.close();
s.close();
}
catch(Exception e){
throw new RuntimeException("文件上传失败!");
}
}
}
class UpLoadClient{
public static void main(String[] args)throws Exception{
Socket s = new Socket("127.0.0.1",10009);
OutputStream ops = s.getOutputStream();
FileInputStream fis = new FileInputStream("D:\\demo.txt");
byte[] arr = new byte[1024];
int len =0;
while((len = fis.read(arr))!=-1){
ops.write(arr,0,len);
}
s.shutdownOutput();//调用此方法以后上传线程就可以收到一个-1的读取结束标志位
InputStream ips = s.getInputStream();
byte[] bt = new byte[1024];
int num = ips.read(bt);
System.out.println(new String(bt,0,num));
fis.close();
s.close();
}
}
public class UpLoadServer{
public static void main(String[] args)throws Exception{
ServerSocket ss = new ServerSocket(10009);
//此处共享,就不用每个线程都在创建一个UpLoadThread对象啦,且可以共享count成员变量
UpLoadThread ult = new UpLoadThread();
while(true){
Socket s = ss.accept();
ult.setSocket(s);
new Thread(ult).start();
}
}
}
搞了挺长时间也就修了修边边角角的东西,感觉这些细节跟你抛出的那个异常也没啥关系,现在在我这是运行正常啦,另外请教下
s.shutdownOutput();//调用此方法以后上传线程就可以收到一个-1的读取结束标志位
我关于这句话的了解对不对,感觉是这个样子
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |