java-Socket文件上传/进度条

客户端代码:
 
1、客户端运行程序:
package wtb.khd;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
public class KHD{
 private boolean isnoClose = true;
 public boolean isIsnoClose() {
  return isnoClose;
 }
 public void setIsnoClose(boolean isnoClose) {
  this.isnoClose = isnoClose;
 }
 public static void main(String args[]){
  final KHD khd = new KHD();
  String filePath = "D:\\文件.zip";
  khd.setIsnoClose(true);
  File upload = new File(filePath);
  long fileLength = upload.length();
  String fileName = upload.getName();
  try {
   Socket client = null;
   client = new Socket("localhost",8888); //"localhost"--->服务器端IP
   OutputStream out = client.getOutputStream();
   DataOutputStream dos = new DataOutputStream(out);
   dos.writeUTF("文件名前缀_"+fileName);
   dos.writeLong(fileLength);
   FileInputStream fis = new FileInputStream(upload);
   byte[] buffer = new byte[2048];
   int len = 0;
   double scbl = 0; //文件上传比例
   int scdx = 0;  //文件上传大小
   final JinDuBar jdb = new JinDuBar("文件上传",System.getProperty("user.dir")+" \\bin\\image\\jindutiao.gif ");
   String[] uploadInfo = new String[]{"正在上传文件:" + filePath, "文件名称:"+ fileName,
     "上传文件大小:"+fileLength+"字节", "已上传:0字节", "上传比例:0%"};
   JLabel[] labels = jdb.getLabels();
   for(int lxb = 0; lxb<labels.length; lxb++){
    labels[lxb].setText(uploadInfo[lxb]);
   }
   JProgressBar p = jdb.getProgress();
   JButton closeBtn = jdb.getCloseBtn();
  
   closeBtn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
     jdb.dispose();
     khd.setIsnoClose(false);
    }
   });
   while ((len = fis.read(buffer)) > 0 && khd.isnoClose) {
    Thread.sleep(100);
    scdx += len;
    scbl = (double)scdx/fileLength;
    int bl = (int)(scbl*100);
    dos.write(buffer, 0, len);
    p.setValue(bl);
    p.setString(bl+"%");
    String[] gxsc = new String[]{"已上传:"+scdx+"字节", "上传比例:"+bl+"%"};
    for(int lxb = 0; lxb<gxsc.length; lxb++){
     labels[lxb+3].setText(gxsc[lxb]);
    }
   }
   jdb.dispose();
   out.close();
   fis.close();
   client.close();
  } catch (Exception e1) {
   e1.printStackTrace();
  }
 }
}
 
/****************************/
2、进度条
package wtb.util;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JWindow;
@SuppressWarnings("serial")
public class JinDuBar extends JWindow{
 private JProgressBar progress;
 private JButton btn;
 private JLabel[] labels = new JLabel[5];
 private JButton closeBtn;
 public JProgressBar getProgress() {
  return progress;
 }
 public void setProgress(JProgressBar progress) {
  this.progress = progress;
 }
 public JButton getBtn() {
  return btn;
 }
 public void setBtn(JButton btn) {
  this.btn = btn;
 }
 public JLabel[] getLabels() {
  return labels;
 }
 public void setLabels(JLabel[] labels) {
  this.labels = labels;
 }
 public JButton getCloseBtn() {
  return closeBtn;
 }
 public void setCloseBtn(JButton closeBtn) {
  this.closeBtn = closeBtn;
 }
 public JinDuBar(String title,String bgImg){
  setAlwaysOnTop(true);
  setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  JPanel splash = new JPanel(new BorderLayout());
  JPanel top = new JPanel();
  top.setBackground(new Color(255,153,204));
  BorderLayout toplay = new BorderLayout();
  top.setLayout(toplay);
  JLabel tt = new JLabel(title);
  ImageIcon cloImg = new ImageIcon(System.getProperty("user.dir") + "/bin/image/4.png");
  closeBtn = new JButton("close ",cloImg);
  closeBtn.setBackground(new Color(255,153,204));
  top.add(tt, BorderLayout.CENTER);
  top.add(closeBtn, BorderLayout.EAST);
  top.add(new JLabel("   "), BorderLayout.WEST);
  splash.add(top,BorderLayout.NORTH);
  ImageIcon img = new ImageIcon(bgImg);
  btn = new JButton(img);
  getLayeredPane().add(btn, new Integer(Integer.MIN_VALUE));
        btn.setBounds(0,0,img.getIconWidth(),img.getIconHeight());
        GridLayout gl = new GridLayout(this.getLabels().length,1); //labels.length行1列
        btn.setLayout(gl);
        for(int i = 0; i<labels.length; i++){
         this.getLabels()[i] = new JLabel("000"+i);
         btn.add(labels[i]);
        }
  splash.add(btn, BorderLayout.CENTER);
  progress = new JProgressBar(1, 100);
  progress.setStringPainted(true);
  progress.setBorderPainted(false);
  progress.setString("0%");
  progress.setBackground(Color.WHITE);
  splash.add(progress, BorderLayout.SOUTH);
  setContentPane(splash);
  Dimension screen = getToolkit().getScreenSize();
  setSize(img.getIconWidth(), img.getIconHeight()+60);
  setLocation((screen.width - getSize().width)/2, (screen.height - getSize().height)/2);
  new DragJWindow(this, splash);  //设置窗口可拖动 www.2cto.com
  setVisible(true);
 }
}
/********************************/
3、设置Window窗口可拖动
package wtb.util;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
public class DragJWindow {
    private Window fWindow;
    private Component fComponent;
    private int dX;
    private int dY;
    public DragJWindow(Window window, Component component) {
        fWindow = window;
        fComponent = component;
        fComponent.addMouseListener(createMouseListener());
        fComponent.addMouseMotionListener(createMouseMotionListener());
    }
    private MouseListener createMouseListener() {
        return new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                Point clickPoint = new Point(e.getPoint());
                SwingUtilities.convertPointToScreen(clickPoint, fComponent);
                dX = clickPoint.x - fWindow.getX();
                dY = clickPoint.y - fWindow.getY();
            }
        };
    }
    private MouseMotionAdapter createMouseMotionListener() {
        return new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                Point dragPoint = new Point(e.getPoint());
                SwingUtilities.convertPointToScreen(dragPoint, fComponent);
                fWindow.setLocation(dragPoint.x - dX, dragPoint.y - dY);
            }
        };
    }
}
/******************************************/
/******************************************/
服务器端:
1、服务器端运行程序
package wtb.fwq;
import java.net.ServerSocket;
import java.net.Socket;
import wtb.fwq.UploadThread;
public class UploadServer {
 public final static String fileDir = "E:\\wtb";
 public static void main(String args[]) throws Exception {
  ServerSocket server = null ;
  Socket client = null ;
  server = new ServerSocket(8888);
  while(true){
   client = server.accept();
   //为每个用户设置一个线程
   UploadThread uft = new UploadThread(client, fileDir);
   new Thread(uft).start();
  }
 }
}
 
/*************************************/
2、为每个用户设置一个线程的线程类
package wtb.fwq;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class UploadThread implements Runnable {
 private Socket client;
 private String fileDir;
 private String fileName;
 public UploadThread(Socket client, String fileDir){
  this.client = client;
  this.fileDir = fileDir;
 }
 public void run(){
  InputStream in = null ;
  FileOutputStream fos = null;
  try {
   in = client.getInputStream();
   DataInputStream dis = new DataInputStream(in);
   fileName = dis.readUTF();
   long fileLength = dis.readLong();
   long xzdx = 0;
   fos = new FileOutputStream(fileDir+File.separator+fileName);
   byte[] buffer = new byte[1024];
   int len = 0;
   while ((len = dis.read(buffer)) > 0)
   {
    fos.write(buffer, 0, len);
    xzdx += len;
   }
   fos.flush();
   fos.close();
   in.close();
   client.close() ;
   if(xzdx != fileLength){  //如果文件未传完,则删除传到服务器端的文件
    File f = new File(fileDir+File.separator+fileName);
    f.delete();
   }
  }catch(Exception e){
   System.out.println("异常!!!!");
  }
 }
}
/************************/
运行结果视图:

\

转载自:http://www.2cto.com/kf/201203/122870.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值