#######################################
客户端
- ###UploadPicClient.java
- public class UploadPicClient {
- /**
- * @param args
- * @throws IOException
- * @throws
- */
- public static void main(String[] args) throws IOException {
- System.out.println("上传图片客户端运行......");
- //1,创建socket。
- Socket s = new Socket("192.168.1.223", 10007);
-
- //2,读取源图片。
- File picFile = new File("tempfile\\1.jpg");
- FileInputStream fis = new FileInputStream(picFile);
-
- //3,目的是socket 输出流。
- 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);
- System.out.println(new String(bufIn,0,lenIn));
-
- //关闭。
- fis.close();
- s.close();
- }
- }
##################################################################
服务端
- ###UploadPicServer.java
- public class UploadPicServer {
- /**
- * @param args
- * @throws IOException
- */
- public static void main(String[] args) throws IOException {
- System.out.println("上传图片服务端运行......");
- // 创建server socket 。
- ServerSocket ss = new ServerSocket(10007);
- while (true) {
- // 获取客户端。
- Socket s = ss.accept();
-
- //实现多个客户端并发上传,服务器端必须启动做个线程来完成。
- new Thread(new UploadPic(s)).start();
- }
- }
- }
- ###UploadPic.java
- public class UploadPic implements Runnable {
- private Socket s;
- public UploadPic(Socket s) {
- this.s = s;
- }
- @Override
- public void run() {
- try {
- String ip = s.getInetAddress().getHostAddress();
- System.out.println(ip + ".....connected");
- // 读取图片数据。
- InputStream in = s.getInputStream();
- // 写图片数据到文件。
- File dir = new File("e:\\uploadpic");
- if (!dir.exists()) {
- dir.mkdir();
- }
- // 为了避免覆盖,通过给重名的文件进行编号。
- int count = 1;
- File picFile = new File(dir, ip + "(" + count + ").jpg");
- while (picFile.exists()) {
- count++;
- picFile = new File(dir, ip + "(" + count + ").jpg");
- }
- FileOutputStream fos = new FileOutputStream(picFile);
- byte[] buf = new byte[1024];
- int len = 0;
- while ((len = in.read(buf)) != -1) {
- fos.write(buf, 0, len);
- }
- // 给客户端一个回馈信息。
- OutputStream out = s.getOutputStream();
- out.write("上传成功".getBytes());
- // 关闭资源。
- fos.close();
- s.close();
- } catch (IOException e) {
- }
- }
- }