您的当前位置:首页正文

socket实现文件传输

2021-10-12 来源:伴沃教育
package Client; import java.io.*; import java.net.*;

import test.FTPClient;

public class FtpClient2 { /** * @param args */ private ServerSocket server = null; Socket socket = null; DataOutputStream dout = null;//写Socket 的输出流 DataInputStream din = null; DataOutputStream writer = null; DataInputStream reader = null;//读取本地文件的输入流 public boolean connection; //请求建立连接 public void ClientStart(String hostname,int port){ try{ socket = new Socket(hostname,port); dout = new DataOutputStream(socket.getOutputStream()); din = new DataInputStream(socket.getInputStream()); dout.writeUTF(\"客户端请求建立连接······\"); System.out.println(din.readUTF()); connection = true; }catch(Exception e){ e.printStackTrace(); connection = false; } } //客户端关闭连接 public void ClientClose(){ try{ socket.close(); din.close(); dout.close(); }catch(Exception e){ e.printStackTrace(); } } //向服务器发送文件

public void PutFile(String localFileName,String remoteFileName){ int progress = 0; int bufferSize=10240;//10k

byte[] buf=new byte[bufferSize]; int read=0; try{ if(socket==null) return;

File file=new File(localFileName); if(!file.exists()){//检查文件是否存在

System.out.println(\"本地文件不存在,请查看文件名是否写错\"); return; }

reader=new DataInputStream(new BufferedInputStream(new FileInputStream(file)));//初始化本地文件读取流

dout=new DataOutputStream(socket.getOutputStream()); //将指令和文件名发送到Socket 的输出流中

dout.writeUTF(\"put \"+remoteFileName);//将远程文件名发送出去 dout.writeLong((long)file.length()); dout.flush();

while (true) { // 传输文件 if (din != null) {

read = reader.read(buf); }

progress += Math.abs(read); if (read == -1) { break; }

dout.write(buf, 0, read);

System.out.println(\"------------文件已发送:\" + (int)(100.0*progress/file.length()) + \"%\");//发送进度显示。 }

dout.flush();

System.out.println(\"文件发送成功!\"); }catch(IOException ex){ ex.printStackTrace(); }finally{ try{

reader.close(); dout.close(); }catch(IOException e){ e.printStackTrace(); } }

} //从服务器接收文件 public void GetFile(String localFileName,String remoteFileName){ int passedlen = 0; int progress = 0 ; long len = 0; int bufferSize=10240;//10k

byte[] buf=new byte[bufferSize]; int read=0; try{

if(socket==null) return; writer=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File(localFileName))));

//将指令和文件名发送到Socket 的输出流中 dout=new DataOutputStream(socket.getOutputStream());

dout.writeUTF(\"get \"+remoteFileName);//将远程文件名发送出去 dout.flush(); //开始接收文件

din = new DataInputStream(new BufferedInputStream(socket.getInputStream())); len = din.readLong();//获取文件长度

System.out.println(\"文件的长度为:\" + len + \"KB\"); System.out.println(\"开始接收文件!\");

System.out.print(\"#>>>>>>>>#>>>>>>>>>#>>>>>>>>>#>>>>>>>>>#>>>>>>>>>#>>>>>>>>>#>>>>>>>>>#\"); while(true){ if(din != null){ read = din.read(buf); } passedlen += read; if(read == -1){ break; } if((int)(passedlen*100.0 / len)- progress > 0){ progress = (int)(passedlen*100.0 / len); System.out.println(); System.out.println(\"----------文件接收了\"+progress+\"%\"); System.out.println(\">>>>>>>>>>\"); } writer.write(buf,0,read); }

writer.flush();

System.out.println(\"数据接收完毕!\"); }catch(IOException ex){ ex.printStackTrace(); }finally{ try{

dout.close(); writer.close(); din.close();

}catch(IOException e){ e.printStackTrace(); } } } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub String localFileName=\"\"; String remoteFileName=\"\"; String hostname = \"127.0.0.1\"; int port = 9439; FtpClient2 ftpc = new FtpClient2(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//用于接收用户输入命令 System.out.println(\"请输入连接命令:\"); String[] Order=br.readLine().split(\" \"); try{ if(Order[0].equals(\"put\")){ //上传文件 ftpc.ClientStart(hostname, port); localFileName=Order[1]; remoteFileName=Order[2]; if(ftpc.connection){ ftpc.PutFile(localFileName, remoteFileName); ftpc.ClientClose(); } } else if(Order[0].equals(\"get\")){ //下载文件 ftpc.ClientStart(hostname, port); localFileName=Order[2]; remoteFileName=Order[1]; if(ftpc.connection){ ftpc.GetFile(localFileName, remoteFileName) ; ftpc.ClientClose();

} }else{ System.out.println(\"命令不正确,正确命令如下:\"); System.out.println(\"put local_filename(全地址) remote_filename\"); System.out.println(\"get remote_filename local_filename(全地址)\"); } }catch(Exception e){ e.printStackTrace(); } } } 、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、 package Service;

import java.io.*; import java.net.*;

public class SocketConnection2 extends Thread{ private Socket socket; private String filePath;

private DataInputStream din=null;//读取Socket 的输入流 private DataOutputStream writer=null;//写文件的输出流 private DataOutputStream dout=null;//写Socket 的输出流 private DataInputStream reader=null;//读文件的输入流 public SocketConnection2(Socket socket,String filePath){ this.socket=socket; this.filePath=filePath; }

public void run(){ if(socket==null) return; try{

//访问Socket 对象的getInputStream 方法取得客户端发送过来的数据 流 din = new DataInputStream(new BufferedInputStream(socket.getInputStream())); String recvInfo = din.readUTF();//取得附带的指令及文件名 put+remotefilename

System.out.println(recvInfo); String[] info=recvInfo.split(\" \");

String fileName=info[1];//获取文件名

if(filePath.endsWith(\"/\")==false&&filePath.endsWith(\"\\\\\")==false){ filePath+=\"\\\\\"; }

filePath+=fileName; if(info[0].equals(\"put\")){

//从客户端上传到服务器 //开始接收文件 writer=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File(filePath))));

dout = new DataOutputStream(socket.getOutputStream()); din = new DataInputStream(new BufferedInputStream(socket.getInputStream())); int bufferSize=10240;//10k

byte[] buf=new byte[bufferSize]; int read=0;

System.out.println(\"接收数据量为:\"+read); while((read = din.read(buf))!=-1){ writer.write(buf,0,read);

System.out.println(\"接收数据量为:\"+read); }

writer.flush();

System.out.println(\"数据接收完毕!\"); }

else if(info[0].equals(\"get\")){ File file=new File(filePath);

if(!file.exists()){//检查文件是否存在

System.out.println(\"本地文件不存在,请查看文件名是否写错\"); return; }

//从服务器下载文件到客户端 reader=new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));

//开始发送文件

int bufferSize=10240;//10k

byte[] buf=new byte[bufferSize];

dout=new DataOutputStream(socket.getOutputStream()); dout.writeLong((long)file.length()); int read=0; int progress = 0;

while (true) { // 传输文件 if (din != null) {

read = reader.read(buf); }

progress += Math.abs(read); if (read == -1) { break; }

dout.write(buf, 0, read);

System.out.println(\"------------文件已发送:\" + (int)(100.0*progress/file.length()) + \"%\");//发送进度显示。 }

dout.flush();

System.out.println(\"发送成功!\"); }

}catch(IOException ex){ ex.printStackTrace(); }finally{ try{

//out.close(); din.close();

if(writer!=null)writer.close(); if(reader!=null)reader.close(); socket.close(); }catch(IOException e){ e.printStackTrace(); }

} } } ············································································· package Service;

import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.*;

public class FtpService2{ private int port; private String host; private String dirPath; Socket socket = null;

private static ServerSocket server; private DataOutputStream dout = null; private DataInputStream din = null;

public FtpService2(int port,String dirPath){ this.port=port; this.server=null; this.dirPath=dirPath; }

public void ServiceStart() { if(server == null){ try{ server = new ServerSocket(port);//建立socket监听 System.out.println(\"服务器对端口进行监听······\"); while(true){ socket = server.accept(); dout = new DataOutputStream(socket.getOutputStream()); din = new DataInputStream(socket.getInputStream()); System.out.println(\"----------客户端消息:\"+din.readUTF()); System.out.println(\"----------客户端IP地址:\"+socket.getInetAddress()); System.out.println(\"----------客户端端口号是:\"+socket.getPort()); System.out.println(\"----------本地端口号是:\"+socket.getLocalPort()); dout.writeUTF(socket.getInetAddress()+\"服务器同意并建立连接!\"); new SocketConnection2(socket,this.dirPath).run(); } }catch(Exception e){ e.printStackTrace(); } } }

public static void main(String[] args){ int port=9439;

String dirPath=\"G:\\\\\";

new FtpService2(port,dirPath).ServiceStart(); } }

因篇幅问题不能全部显示,请点此查看更多更全内容