标签:
上传图片注意的问题:
解决:
TCP上传图片的客户端:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class UpLoadPicClient { public static void main(String[] args) throws Exception, IOException { System.out.println("客户端开启......"); //1.创建socket客户端 Socket s = new Socket("192.168.17.1",10000); File picFile = new File("1.jpg"); FileInputStream fis = new FileInputStream(picFile); OutputStream out = s.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; while((len = fis.read(buf))!=-1){ out.write(buf, 0, len); } //告诉服务端写完了 s.shutdownOutput(); //读取服务器端的数据 InputStream in = s.getInputStream(); byte[] bufIn =new byte[1024]; int lenIn = in.read(bufIn); String str = new String(bufIn,0,lenIn); System.out.println(str); fis.close(); s.close(); } }
TCP上传图片的服务端:
import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class UpLoadPicServer { public static void main(String[] args) throws Exception { System.out.println("服务端开启....."); //服务端对象 ServerSocket ss = new ServerSocket(10000); while(true){//服务器端一直是开启状态 Socket s = ss.accept();//主线程唯一的任务是不断的等待客户端的连接 //至于每一个连接进来的客户端索要进行的任务,交给其他线程来完成 //这就实现了多客户端的并发访问 //这就是服务器端的原理 new Thread(new UpLoadPic(s)).start();//为每一个连接上的客户端开辟一条线程 } // ss.close(); //服务器端就不需要关闭了 /* * 服务器端的基本技术: * 1.ServerSocket * 2.IO流 * 3.多线程 */ } }
客户端连接后所要进行的任务(线程):
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class UpLoadPic implements Runnable { private Socket s; public UpLoadPic(Socket s) { super(); this.s = s; } @Override public void run() { String ip = s.getInetAddress().getHostAddress(); System.out.println(ip+"...connected"); File file = getFile("server_pic",ip);//服务端将图片保存的位置 FileOutputStream fos; try { fos = new FileOutputStream(file); InputStream in = s.getInputStream(); int len = 0; byte[] buf = new byte[1024]; while((len = in.read(buf))!=-1){ fos.write(buf,0,len); } //回馈客户端数据 OutputStream out = s.getOutputStream(); out.write("上传图片成功".getBytes()); fos.close(); s.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static File getFile(String dir,String ip) { File pic_dir = new File(dir); if(!pic_dir.exists()){ pic_dir.mkdir(); } int count = 1; File file = new File(pic_dir,ip+"("+count+").jpg");//解决图片重名的问题 while(file.exists()){ count++; file = new File(pic_dir,ip+"("+count+").jpg"); } return file; } }
标签:
原文地址:http://www.cnblogs.com/qjlbky/p/5932231.html