1: 客户端代码:
@Test
public void socketClient() throws IOException{
Socket s = null;
String filepath="F:\\yingtao.inw";
File file = new File(filepath);
s=new Socket("127.0.0.1",10000);
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
try {
long fileSize=file.length();
System.out.println("fileSize--->"+fileSize);
String fileName=file.getName();
//将文件名及长度传给接受端
ps.writeUTF(fileName);
ps.flush();
//将文件长度传给接受端
ps.writeLong(fileSize);
ps.flush();
byte[] buf = new byte[1024];
while(true){
int size=0;
int len=fis.read(buf,0,1024);
size+=len;
if(len==-1){
break;
}
ps.write(buf,0,len);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
if(ps!=null){
ps.flush();
ps.close();
}
if(fis!=null)
fis.close();
if(s!=null)
s.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
2:接受端代码。
@Test
public void Socket_Server(){
ServerSocket ss = null;
try {
ss = new ServerSocket(10000);
System.out.println("等待客户端的连接 !");
int i=1;
while(true){
Socket s = ss.accept();
System.out.println("第"+i+"客户端连接进来了 !");
AcceptFileThread at = new AcceptFileThread(s,i);
at.start();
i++;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
class AcceptFileThread extends Thread{
private Socket s ;
private int fileNumber;
public AcceptFileThread(Socket s ,int fileNumber){
this.s=s;
this.fileNumber=fileNumber;
}
@Override
public void run() {
// TODO Auto-generated method stub
DataInputStream in = null;
DataOutputStream out = null;
try {
in = new DataInputStream(new BufferedInputStream(s.getInputStream()));
System.out.println("第 "+fileNumber+" 文件开始上传");
String fileName=in.readUTF();
System.out.println("文件名称---->"+fileName);
long fileSize=in.readLong();
System.out.println("文件长度---> "+fileSize);
System.out.println("开始接受文件!");
StringBuilder builder = new StringBuilder();
builder.append("F:\\server_socket\\").append(fileName);
File savefile = new File(builder.toString());
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(savefile)));
byte[] buff = new byte[1024];
int size=0;
while(true){
int len=in.read(buff,0,1024);
System.out.println("len--->"+len);
if(len==-1){
break;
}
out.write(buff,0,len);
size+=len;
System.out.println("size---->"+size);
System.out.println("文件接受了 "+(size*100/fileSize)+"%");
}
System.out.println("文件 "+fileNumber+"接受完成!");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
if(out!=null){
out.flush();
out.close();
}
if(in!=null){
in.close();
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
super.run();
}
}