JAVA中传输图片的示例

来源:互联网 发布:win10系统里面装mac 编辑:程序博客网 时间:2024/06/16 17:23

利用JAVA中的字节流传输图片

服务端代码

<span style="font-family:KaiTi_GB2312;font-size:18px;">Serverpackage net;   import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket;   public class DataSocketServer {     final public static int DEFAULT_PORT = 4848;     final public static String FILE_DIR = "D:/";       public static void main(String[] args) {         ServerSocket server = null;         try {             server = new ServerSocket(DEFAULT_PORT);               while (true) {                 new Thread(new RequestProcessorTask(server.accept())).start();             }         } catch (IOException e) {             e.printStackTrace();         }     }       static class RequestProcessorTask implements Runnable {         private Socket socket = null;           public RequestProcessorTask(Socket socket) {             this.socket = socket;         }           public void run() {             try {                 boolean isEnd = false;                   BufferedInputStream in = new BufferedInputStream(socket.getInputStream());                   while (!isEnd) {                     int d = -1;                     StringBuilder header = new StringBuilder();                       while ((d = in.read()) != '\r') {                         if (d == -1) {                             isEnd = true;                             break;                         }                         header.append((char) d);                     }                     if (!isEnd) {                         String[] parms = header.toString().split(";");                           FileOutputStream out = new FileOutputStream(FILE_DIR + parms[0]);                         long size = Long.parseLong(parms[1]);                           while (size > 0 && (d = in.read()) != -1) {                             out.write(d);                             size--;                         }                           out.flush();                         out.close();                     }                 }                 in.close();             } catch (IOException e) {                 throw new RuntimeException("获取客户端输入流失败", e);             }         }     } }</span>
客户端代码

<span style="font-family:KaiTi_GB2312;font-size:18px;">import java.io.BufferedOutputStream; import java.io.File;import java.io.FileInputStream; import java.io.IOException; import java.net.Socket;  public class DataSocket {     public static void main(String[] args) throws IOException {        File img1 = new File("e:/a.png");    File img2 = new File("e:/b.png");           Socket socket = new Socket("127.0.0.1", 4848);         String header1 = "a.png;" + img1.length();         String header2 = "b.png;" + img2.length();          BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());      FileInputStream in = new FileInputStream(img1);       FileInputStream in2 = new FileInputStream(img2);        byte[] buffer = new byte[8192];         int readBytes = -1;          out.write(header1.getBytes());      out.write("\r".getBytes());       out.flush();                  while ((readBytes = in.read(buffer)) != -1) {  out.write(buffer, 0, readBytes);        }       out.flush();        out.write(header2.getBytes());      out.write("\r".getBytes());      out.flush();                  while ((readBytes = in2.read(buffer)) != -1){            out.write(buffer, 0, readBytes);     }       out.flush();          in.close();      in2.close();       out.flush();        out.close();   }} </span>




单次图片发送可以这样使用,不过我在代码中同时传数据和图片就会出现问题。

问题原因是:

传图片的用的也是建立的socket通道,在每次传完图片后关闭socket连接,再使用该socket就会出错。

解决办法:

在发送玩图片后发送一个结束标志给接收端,接收端接收到这个接收标志就结束接收。接收端可以实现一次接收多张图片,直到接收到结束标志再结束,发送端一次发送一张图片。

优化后代码如下:

<span style="font-family:KaiTi_GB2312;font-size:18px;">//接收图片public void receive_picture()    {        try {           boolean isEnd = false;             BufferedInputStream in = new BufferedInputStream(socket.getInputStream());             while (!isEnd) {                  int d = -1;                  StringBuilder header = new StringBuilder();                  while ((d = in.read()) != '\r') {                       if (d == -1) {                             isEnd = true;                             break;                         }                         header.append((char) d);                     }                     if (!isEnd) {                         String[] parms = header.toString().split(";");                        if(parms[1].equals("end"))                        {                            isEnd = true;                            break;                        }                        FileOutputStream out = new FileOutputStream("E:/image/"+ parms[0]);                        System.out.println("我的天: "+"E:/image/"+parms[0]);                        long size = Long.parseLong(parms[1]);                         while (size > 0 && (d = in.read()) != -1) {                             out.write(d);                             size--;                         }                         out.flush();                         out.close();                     }                 }                 //in.close();            } catch (IOException e) {                 throw new RuntimeException("获取客户端输入流失败", e);             }     }</span>

<span style="font-family:KaiTi_GB2312;font-size:18px;">//发送图片public void send_picture(String path){byte[] buffer = new byte[8192];         int readBytes = -1;   try{File image = new File(path);FileInputStream in = new FileInputStream(path); String parms[] = path.split("/");String header = parms[2]+";"+image.length();out.write(header.getBytes());      out.write("\r".getBytes());           out.flush();                  while ((readBytes = in.read(buffer)) != -1) {  out.write(buffer, 0, readBytes);        }       out.flush();   in.close();//System.out.println("发送成功?");}catch(FileNotFoundException e){}catch(IOException e){}}</span>

发送完后发送接收标志

<span style="font-family:KaiTi_GB2312;font-size:18px;">for(int j=0;j<shop_amount;j++){send_picture(seller[j].Seller_imagePath);}out.write("end;end".getBytes());out.write("\r".getBytes());</span>


0 0
原创粉丝点击