• java TCP并发实现文件上传---转载(PS:适合java1.6之前)


    /**
    客户端
    1、服务端点
    2、读取客户端已有的文件数据
    3、通过socket输出流发给服务端
    4、读取服务端反馈信息
    5、关闭
    **/
    import java.io.*;
    import java.net.*;
    class  UploadClient
    {
    public static void main(String[] args) throws Exception
    {
    if(args.length != 1)
    {
    System.out.println("未选择文件!!!");
    return;
    }
    File file = new File(args[0]);
    if(!(file.exists() && file.isFile()))
    {
    System.out.println("该文件不存在或者该文件不是一个文件!!!");
    return;
    }
    if(!(file.getName().endsWith(".jpg")))
    {
    System.out.println("文件格式错误!!!");
    return;
    }
    if(file.length() > 1024*1024*5)
    {
    System.out.println("文件太大!!!");
    return;
    }
    Socket s = new Socket("202.194.240.74",4444);
    FileInputStream fis = new FileInputStream(file);
    OutputStream out = s.getOutputStream();
    byte[] buf = new byte[1024];
    int len = 0;
    while((len = fis.read(buf))!=-1)
    {
    out.write(buf,0,len);//这一步有问题,怎么解决?
    }
    //数据已经完成的时候执行shutdownOutput
    s.shutdownOutput();
    InputStream is = s.getInputStream();
    byte[] bufin = new byte[1024];
    int lenin = is.read(bufin);
    System.out.println(new String(bufin,0,lenin));
    fis.close();
    s.close();
    }
    }
    /**
    线程
    */
    class UploadThread implements Runnable
    {
    private Socket s;
    UploadThread(Socket S)
    {
    this.s = s;
    }
    public void run()
    {
    int count = 1;
    String ip = "111";
    try
    {
    System.out.println(ip+"连接");
    InputStream is = s.getInputStream();
    File file = new File(ip+"("+(count++)+")"+".jpg");
    while(file.exists())
    file = new File(ip+"("+(count++)+")"+".jpg");
    FileOutputStream fos = new FileOutputStream(file);
    byte[] buf = new byte[1024];
    int len = 0;
    while((len = is.read(buf))!=-1)
    {
    fos.write(buf,0,len);
    }
    OutputStream out = s.getOutputStream();
    out.write("上传成功".getBytes());
    fos.close();
    s.close();
    }
    catch(Exception e)
    {
    throw new RuntimeException(ip+"上传失败"+e);
    }
    }
    }
    /**
    服务器端
    */
    class  UploadServer
    {
    public static void main(String[] args) throws Exception
    {
    ServerSocket ss = new ServerSocket(4444);
    while(true)
    {
    Socket s = ss.accept();
    new Thread(new UploadThread(s)).start();
    }
    }
    }
  • 相关阅读:
    寒假13
    寒假作业十二
    寒假12
    寒假作业十一
    寒假11
    寒假作业九
    寒假10
    寒假作业九
    寒假9
    寒假作业八
  • 原文地址:https://www.cnblogs.com/kevinfuture/p/4277805.html
Copyright © 2020-2023  润新知