使用Socket传输图片

今天写了个用socket传输图片的窗口。。。。

下面是代码:

服务器:

package Inernet;

import java.awt.BorderLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

public class pictureServer extends JFrame{
    private JPanel contentpane;
    private JTextField path;
    private JButton choose_pic;
    private JButton send;
    private Image sendImg;
    private Image recevieImg;
    private File imgFile;
    private SendImagePanel sendImgePanel;
    private ReceviceImgPanel receviceImgPanel;
    private DataOutputStream out;
    private DataInputStream in;
    private ServerSocket server;
    private Socket socket;
    
/*
 * Luanch the main
 */
    public static void main(String [] args)
    {
        pictureServer frame=new pictureServer();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.getServer();
    }
    
    /*
     * serverSocke
     */
     public void getServer()
     {
         try {
            server=new ServerSocket(6000);  //服务器实例化
            while(true)
            {    
                socket=server.accept();       //socket实例化
                System.out.println("连接成功");
                out=new DataOutputStream(socket.getOutputStream());  //获得输出流对象
                in=new DataInputStream(socket.getInputStream());     //获得输入流对象
                getClientInfo();    //读取图片方法
            }
                
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
     }
    private void getClientInfo() {
        // TODO Auto-generated method stub
//        if(imgFile!=null)
//        {
            long lengths;
            try {
                    lengths = in.readLong();   //读取图片文件长度文件
                    byte[] bt=new byte[(int)lengths];   //创建长度为length的字节数组 bt
                    for(int i=0;i<bt.length;i++)   //读取字节信息并存储到字节数组
                    {
                        bt[i]=in.readByte();   
                    }
                    recevieImg=new ImageIcon(bt).getImage();  //创建图像对象
                    receviceImgPanel.repaint();    //重新描绘图像
            } catch (IOException e) {
                // TODO Auto-generated catch block
//                e.printStackTrace();      在关闭流时会跳出错误
            }finally{
                try{
                    if(in!=null)
                    {
                        in.close();
                    }
                    if(socket!=null)
                    {
                        socket.close();
                    }
                }catch (IOException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
            
//        }
    }
    /*
     * create the frame
     */
    public pictureServer()
    {
        contentpane=new JPanel();
        setContentPane(contentpane);
        setBounds(100, 100, 379, 260);
        contentpane.setLayout(new BorderLayout());
        JPanel toppanel=new JPanel();
        contentpane.add(toppanel,BorderLayout.NORTH);
        toppanel.add(new JLabel("路径:"));
        path=new JTextField(10);
        toppanel.add(path);
        choose_pic=new JButton("选择图片");
        toppanel.add(choose_pic);
        sendImgePanel=new SendImagePanel();
        receviceImgPanel=new ReceviceImgPanel();
        choose_pic.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                JFileChooser filterChoose=new JFileChooser();   //创建文件选择器
                FileNameExtensionFilter fileFilter=new FileNameExtensionFilter("图像文件(JPE/GIF/BMP)", "JPG","JPEG","GIF","BMF"); //创建过滤器并设置为图片格式
                filterChoose.setFileFilter(fileFilter);    
                int flag= filterChoose.showOpenDialog(null); //显示打开对话框 返回状态
                if(flag==JFileChooser.APPROVE_OPTION)      //APPROVE_OPTION是个整型常量,代表0。就是说当返回0的值我们才执行相关操作     
                {
//                    System.out.println("111");
                    imgFile=filterChoose.getSelectedFile();    //获得选择文件
                }
                if(imgFile!=null)
                {
//                    System.out.println("22");
                    path.setText(imgFile.getAbsolutePath());    //path中显示imgfile的绝对路径
                    try {
                        sendImg=ImageIO.read(imgFile);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                sendImgePanel.repaint();
                    
            }
        });
        send=new JButton("发送");
        toppanel.add(send);
        send.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                DataInputStream dis=null;
                long length;
                if(imgFile!=null)
                {
                    length=imgFile.length();
                    try {
                        dis=new DataInputStream(new  FileInputStream(imgFile));   //初始化dis
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }else
                {
                    JOptionPane.showMessageDialog(null, "还没有选择图片!");
                    return;
                }
                try {
//                    System.out.println(length);
                    out.writeLong(length);     //输出图片文件长度
                    byte[] bt =new byte[(int) length];
                    int len=-1;
                    while((len=dis.read(bt))!=-1)    //如果读取到的不是-1,即读取结束 并将图片读取到字节数组中
                    {
                        System.out.println("222");
                        out.write(bt);    //发送数组
                        System.out.println(len);
                    }
                        
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        
        JPanel midpanel=new JPanel();
        midpanel.setLayout(new BorderLayout());
        contentpane.add(midpanel,BorderLayout.CENTER);
        JPanel panel=new JPanel();
        panel.setLayout(new GridLayout(1,2));
        midpanel.add(panel,BorderLayout.NORTH);
        JLabel label_1=new JLabel("服务器端选择的要发送的图片  ");
        label_1.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
        panel.add(label_1);
        JLabel label_2=new JLabel("接收到客户端发送的图片       ");
        label_2.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
        panel.add(label_2);
        JPanel imgpanel=new JPanel();
        final GridLayout gridLayout = new GridLayout(1,2);
        gridLayout.setVgap(10);
        imgpanel.setLayout(gridLayout);
        midpanel.add(imgpanel,BorderLayout.CENTER);
        imgpanel.add(sendImgePanel);
        imgpanel.add(receviceImgPanel);
    }
    
    //创建面板类
    class SendImagePanel extends JPanel
    {
        public void paint(Graphics g)
        {
//            System.out.println("11");
            if (sendImg != null) {
                 g.clearRect(0, 0, this.getWidth(), this.getHeight());
                g.drawImage(sendImg, 0, 0, this.getWidth(), this.getHeight(),this);
            }
        }
        
    }
    
    class ReceviceImgPanel extends JPanel
    {
        public void paint(Graphics g) {
            g.clearRect(0, 0, this.getWidth(), this.getHeight());
            g.drawImage(recevieImg, 0, 0, this.getWidth(), this.getHeight(),this);
        }
    }
}

客户端:

package Inernet;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

public class pictureClient extends JFrame
{

    private JPanel contentpane;
    private JTextField path;
    private JButton choose_pic;
    private JButton send;
    private SendImgPanel sendImgPanel;
    private ReceviceImgPanel receviceImgPanel;
    private File imgFile;
    private Image sendImg;
    private Image receviceImg;
    private DataInputStream in;
    private DataOutputStream out;
    private Socket client;
    /*
     * lanuch the main
     */
    public static void main(String [] agrs)
    {
        pictureClient frame=new pictureClient();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.createclient();
    }
    
    void createclient()
    {
        try {
            client=new Socket("127.0.0.1",6000);
            while(true)
            {
                if(client!=null && !client.isClosed())
                {
                        in=new DataInputStream(client.getInputStream());
                        out=new DataOutputStream(client.getOutputStream());
                        getServerInf();
                    
                }else
                {
                    client=new Socket("127.0.0.1",6000);
                }
            }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    private void getServerInf() {
        // TODO Auto-generated method stub
//            System.out.println("1231");
            long length;
            try {
                length = in.readLong();
                System.out.println(length);
                byte[] bt=new byte[(int)length];
                for(int i=0;i<bt.length;i++)
                {
                    
                    bt[i]=in.readByte();
                }
                receviceImg=new ImageIcon(bt).getImage();
                receviceImgPanel.repaint();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }finally{
                try{
                    if(in!=null)
                    {
                        in.close();
                    }
                    if(client!=null)
                    {
                        client.close();
                    }
                }catch (IOException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
                
        
    }

    /*
     * clientServer;
     */
    /*
     * create the frame
     */
    public pictureClient()  
    {
        setTitle("客户端");
        setBounds(100, 100, 379, 260);
        contentpane=new JPanel();
        contentpane.setLayout(new BorderLayout());
        setContentPane(contentpane);
        final JPanel toppane=new JPanel();
        contentpane.add(toppane,BorderLayout.NORTH);
        toppane.add(new JLabel("路径:"));
        path=new JTextField(10);
        toppane.add(path);
        choose_pic=new JButton("选择图片");
        toppane.add(choose_pic);
        sendImgPanel=new SendImgPanel();
        receviceImgPanel=new ReceviceImgPanel();
        choose_pic.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                FileNameExtensionFilter filte=new FileNameExtensionFilter("图片文件", "JPG","JPEG","BMF");
                JFileChooser FileChooser=new JFileChooser();
                FileChooser.setFileFilter(filte);
                int flag=FileChooser.showOpenDialog(null);
                if(flag==JFileChooser.APPROVE_OPTION)
                {
                    imgFile=FileChooser.getSelectedFile();
                }
                if(imgFile!=null)
                {
                    path.setText(imgFile.getAbsolutePath());
                    try {
                        sendImg=ImageIO.read(imgFile);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    
                }
                sendImgPanel.repaint();
            }
        });
        send=new JButton("发送");
        toppane.add(send);
        send.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                DataInputStream dis=null;
                long lengh=imgFile.length();
                if(imgFile!=null)
                {
                    try {
                        dis=new DataInputStream(new FileInputStream(imgFile));
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }else
                {
                    JOptionPane.showMessageDialog(null, "请选择图片!");
                    
                }
                try{
                    out.writeLong(lengh);
                byte[] bt=new byte[(int)lengh];
                int len=-1;
                while((len=dis.read(bt))!=-1)
                {
                    out.write(bt);
                    System.out.println("client");
                }
                }catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        });
        final JPanel midpane=new JPanel();
        midpane.setLayout(new BorderLayout());
        contentpane.add(midpane,BorderLayout.CENTER);
        final JPanel font_panel=new JPanel();
        font_panel.setLayout(new GridLayout(1,2));
        midpane.add(font_panel,BorderLayout.NORTH);
        font_panel.add(new JLabel("   客户端选择发送的图片 "));
        font_panel.add(new JLabel("   服务端选择发送的图片 "));
        final JPanel Imgpanel=new JPanel();
        Imgpanel.setLayout(new GridLayout(1,2));
        midpane.add(Imgpanel,BorderLayout.CENTER);
        Imgpanel.add(sendImgPanel);
        Imgpanel.add(receviceImgPanel);
        
        
    }
    private class SendImgPanel extends JPanel{
        public void paint(Graphics g)
        {
//            System.out.println("111");
            g.clearRect(0, 0, this.getWidth(), this.getHeight());
            g.drawImage(sendImg,0,0, this.getWidth(), this.getHeight(), this);
            
        }
    }
    private class ReceviceImgPanel extends JPanel{
        public void paint(Graphics g)
        {
            g.clearRect(0, 0, this.getWidth(), this.getHeight());
            g.drawImage(receviceImg,0,0, this.getWidth(), this.getHeight(), this);
            
        }
    }
}

用图片传输的时候发现一个问题,就是每次传输完图片都需要关闭输入流,socket,在重建一个socket,(还没去查有什么解决方法,这样不实用),这样导致每次in.readLong()会报无法找到输入流的问题,到不影响运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值