您的位置:首页 > 理论基础 > 计算机网络

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

2015-02-06 18:41 309 查看
/**客户端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(); } }}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: