JAVA中传输图片的示例

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

服务端代码

<span style="font-family:KaiTi_GB2312;font-size:18px;">Server
package 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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值