编程知识 cdmana.com

[question 94] advanced Java technology - network programming 13 (simple chat room 8: using socket to transfer pictures)

Back to city transmission –》《JAVA Building foundation 100 example 》

zero 、 Preface

​ Today is learning JAVA Language The first time to punch in 94 God , Every day I will provide an article for group members to read ( You don't need to pay for a subscription ), After reading the article , According to the idea of problem solving , Do it again . stay Xiaoxuzhu JAVA Community Corresponding 【 Card printing 】 Clock in , Today's task is finished .

​ Because we all study the same article together , So you can ask any questions in the group , Small partners in the group can help you quickly , One can walk very fast , A group of people can go far , There are comrades in arms who study and communicate together , What a lucky thing .

​ After learning , Write your own study report blog , Can be published to Xiaoxuzhu JAVA Community , For the reference of the students .

​ My learning strategy is very simple , Strategy sea + Feynman method of learning . If you can put this 100 All the questions are realized by yourself , That means JAVA Language The foundation has been built successfully . Later advanced learning , You can continue to follow me , Go to the road of architect together .

One 、 Title Description

Topic realization : When using network programming , Need to pass through Socket Pass on the pictures .

Two 、 Their thinking

Create a server class :ServerSocketFrame, Inherit JFrame class

Write a getserver() Method , Instantiation Socket object , Enable 9527 When the port of the service .

Create an input stream object , Used to receive client information .

Let me define one more getClientInfo() Method , Used to receive information sent by the client .

Add an event to the text box : Realize sending weighing information to the client .

Create a client class :ClientSocketFrame, Inherit JFrame class .

Write a connect() Method , Instantiation Socket object , Connect to the local service 9527 Port services .

Let me define one more getClientInfo() Method , Used to receive information sent by the server .

Technical focus :

By using DataInputStream Class read0 Method , Read image file into byte array , And then use DataOutputStream Class from DataOutput Class inheritance write0 Method to output an array of bytes , Thus, the use of Socket The function of transferring pictures .

3、 ... and 、 Code details

ServerSocketFrame

package com.xiaoxuzhu;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
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.*;
import java.net.*;
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.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
/** * Description: * * @author xiaoxuzhu * @version 1.0 * * <pre> *  Modify the record : *  Revised version   Modifier   modification date   Modify the content  * 2022/6/4.1 xiaoxuzhu 2022/6/4 Create * </pre> * @date 2022/6/4 */

public class ServerSocketFrame extends JFrame {
    
    private Image sendImg = null; //  Declare image object 
    private Image receiveImg = null; //  Declare image object 
    private SendImagePanel sendImagePanel = null; //  Declare an image panel object 
    private ReceiveImagePanel receiveImagePanel = null; //  Declare an image panel object 
    private File imgFile = null;//  Declare the... Of the selected picture File object 
    private JTextField tf_path;
    private DataOutputStream out = null; //  Create a flow object 
    private DataInputStream in = null; //  Create a flow object 
    private ServerSocket server; //  Statement ServerSocket object 
    private Socket socket; //  Statement Socket object socket
    private long lengths = -1; //  The size of the picture file 
    public void getServer() {
    
        try {
    
            server = new ServerSocket(9527); //  Instantiation Socket object 
            while (true) {
     //  If the socket is connected 
                socket = server.accept(); //  Instantiation Socket object 
                out = new DataOutputStream(socket.getOutputStream());//  Get the output stream object 
                in = new DataInputStream(socket.getInputStream());//  Get the input stream object 
                getClientInfo(); //  call getClientInfo() Method 
            }
        } catch (Exception e) {
    
            e.printStackTrace(); //  Output exception information 
        }
    }

    private void getClientInfo() {
    
        try {
    
            long lengths = in.readLong();//  Read the length of the picture file 
            byte[] bt = new byte[(int) lengths];//  Create an array of bytes 
            for (int i = 0; i < bt.length; i++) {
    
                bt[i] = in.readByte();//  Read byte information and store it in byte array 
            }
            receiveImg = new ImageIcon(bt).getImage();//  Create an image object 
            receiveImagePanel.repaint();//  Redraw the image 
        } catch (Exception e) {
    
        } finally {
    
            try {
    
                if (in != null) {
    
                    in.close();//  Closed flow 
                }
                if (socket != null) {
    
                    socket.close(); //  Close socket 
                }
            } catch (IOException e) {
    
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
     //  Main method 
        ServerSocketFrame frame = new ServerSocketFrame(); //  Create objects of this class 
        frame.setVisible(true);
        frame.getServer(); //  Calling method 
    }

    public ServerSocketFrame() {
    
        super();
        setTitle(" Server side program ");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 379, 260);

        final JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.NORTH);

        final JLabel label = new JLabel();
        label.setText(" route :");
        panel.add(label);

        tf_path = new JTextField();
        tf_path.setPreferredSize(new Dimension(140, 25));
        panel.add(tf_path);

        sendImagePanel = new SendImagePanel();
        receiveImagePanel = new ReceiveImagePanel();
        final JButton button_1 = new JButton();
        button_1.addActionListener(new ActionListener() {
    
            public void actionPerformed(final ActionEvent e) {
    
                JFileChooser fileChooser = new JFileChooser();//  Create a file selector 
                FileFilter filter = new FileNameExtensionFilter(
                        " image file (JPG/GIF/BMP)", "JPG", "JPEG", "GIF", "BMP");//  Create filters 
                fileChooser.setFileFilter(filter);//  catalog filter 
                int flag = fileChooser.showOpenDialog(null);//  Show open dialog 
                if (flag == JFileChooser.APPROVE_OPTION) {
    
                    imgFile = fileChooser.getSelectedFile(); //  Get the of the selected picture File object 
                }
                if (imgFile != null) {
    
                    tf_path.setText(imgFile.getAbsolutePath());//  Image full path 
                    try {
    
                        sendImg = ImageIO.read(imgFile);//  structure BufferedImage object 
                    } catch (IOException ex) {
    
                        ex.printStackTrace();
                    }
                }
                sendImagePanel.repaint();//  call paint() Method 
            }
        });
        button_1.setText(" Select Picture ");
        panel.add(button_1);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
    
            public void actionPerformed(final ActionEvent e) {
    
                try {
    
                    DataInputStream inStream = null;//  Define data input stream objects 
                    if (imgFile != null) {
    
                        lengths = imgFile.length();//  Get the size of the selected picture 
                        inStream = new DataInputStream(new FileInputStream(imgFile));//  Create an input stream object 
                    } else {
    
                        JOptionPane.showMessageDialog(null, " No picture file has been selected .");
                        return;
                    }
                    out.writeLong(lengths);//  Write the size of the file to the output stream 
                    byte[] bt = new byte[(int) lengths];//  Create an array of bytes 
                    int len = -1;
                    while ((len = inStream.read(bt)) != -1) {
    //  Read image file into byte array 
                        out.write(bt);//  Write byte array to output stream 
                    }
                } catch (IOException e1) {
    
                    e1.printStackTrace();
                }
            }
        });
        button.setText(" Hair   send ");
        panel.add(button);

        final JPanel panel_1 = new JPanel();
        panel_1.setLayout(new BorderLayout());
        getContentPane().add(panel_1, BorderLayout.CENTER);

        final JPanel panel_2 = new JPanel();
        panel_2.setLayout(new GridLayout(1, 0));
        final FlowLayout flowLayout = new FlowLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        panel_2.setLayout(flowLayout);
        panel_1.add(panel_2, BorderLayout.NORTH);

        final JLabel label_1 = new JLabel();
        label_1.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
        label_1.setText(" The image selected by the server to send  ");
        panel_2.add(label_1);

        final JLabel label_2 = new JLabel();
        label_2.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
        label_2.setText(" Received the picture sent by the client  ");
        panel_2.add(label_2);

        final JPanel imgPanel = new JPanel();
        final GridLayout gridLayout = new GridLayout(1, 0);
        gridLayout.setVgap(10);
        imgPanel.setLayout(gridLayout);
        panel_1.add(imgPanel, BorderLayout.CENTER);
        imgPanel.add(sendImagePanel);
        imgPanel.add(receiveImagePanel);
        sendImagePanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
        receiveImagePanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
    }

    //  Create panel class 
    class SendImagePanel extends JPanel {
    
        public void paint(Graphics g) {
    
            if (sendImg != null) {
    
                g.clearRect(0, 0, this.getWidth(), this.getHeight());//  Clear the contents of the drawing context 
                g.drawImage(sendImg, 0, 0, this.getWidth(), this.getHeight(),
                        this);//  Draw a picture of the specified size 
            }
        }
    }

    //  Create panel class 
    class ReceiveImagePanel extends JPanel {
    
        public void paint(Graphics g) {
    
            if (receiveImg != null) {
    
                g.clearRect(0, 0, this.getWidth(), this.getHeight());//  Clear the contents of the drawing context 
                g.drawImage(receiveImg, 0, 0, this.getWidth(),
                        this.getHeight(), this);//  Draw a picture of the specified size 
            }
        }
    }
}

ClientSocketFrame

package com.xiaoxuzhu;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
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.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.ImageIcon;
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.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

/** * Description: * * @author xiaoxuzhu * @version 1.0 * * <pre> *  Modify the record : *  Revised version   Modifier   modification date   Modify the content  * 2022/6/4.1 xiaoxuzhu 2022/6/4 Create * </pre> * @date 2022/6/4 */

public class ClientSocketFrame extends JFrame {
    
    private Image sendImg = null; //  Declare image object 
    private Image receiveImg = null; //  Declare image object 
    private SendImagePanel sendImagePanel = null; //  Declare an image panel object 
    private ReceiveImagePanel receiveImagePanel = null; //  Declare an image panel object 
    private File imgFile = null;//  Declare the... Of the selected picture File object 
    private JTextField tf_path;
    private DataInputStream in = null; //  Create a flow object 
    private DataOutputStream out = null; //  Create a flow object 
    private Socket socket; //  Statement Socket object 
    private Container cc; //  Statement Container object 
    private long lengths = -1;//  The size of the picture file 

    private void connect() {
     //  Connection socket method 
        try {
     //  The catching 
            socket = new Socket("127.0.0.1", 9527); //  Instantiation Socket object 
            while (true) {
    
                if (socket != null && !socket.isClosed()) {
    
                    out = new DataOutputStream(socket.getOutputStream());//  Get the output stream object 
                    in = new DataInputStream(socket.getInputStream());//  Get the input stream object 
                    getServerInfo();//  call getServerInfo() Method 
                } else {
    
                    socket = new Socket("127.0.0.1", 9527); //  Instantiation Socket object 
                }
            }
        } catch (Exception e) {
    
            e.printStackTrace(); //  Output exception information 
        }
    }

    public static void main(String[] args) {
     //  Main method 
        ClientSocketFrame clien = new ClientSocketFrame(); //  Create this example of an object 
        clien.setVisible(true); //  Show form 
        clien.connect(); //  Call the connection method 
    }

    private void getServerInfo() {
    
        try {
    
            long lengths = in.readLong();//  Read the length of the picture file 
            byte[] bt = new byte[(int) lengths];//  Create an array of bytes 
            for (int i = 0; i < bt.length; i++) {
    
                bt[i] = in.readByte();//  Read byte information and store it in byte array 
            }
            receiveImg = new ImageIcon(bt).getImage();//  Create an image object 
            receiveImagePanel.repaint();//  Redraw the image 
        } catch (Exception e) {
    
        } finally {
    
            try {
    
                if (in != null) {
    
                    in.close();//  Closed flow 
                }
                if (socket != null) {
    
                    socket.close(); //  Close socket 
                }
            } catch (IOException e) {
    
                e.printStackTrace();
            }
        }
    }

    /** * Create the frame */
    public ClientSocketFrame() {
    
        super();
        setTitle(" Client program ");
        setBounds(100, 100, 373, 257);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.NORTH);

        final JLabel label = new JLabel();
        label.setText(" route :");
        panel.add(label);

        tf_path = new JTextField();
        tf_path.setPreferredSize(new Dimension(140, 25));
        panel.add(tf_path);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
    
            public void actionPerformed(final ActionEvent e) {
    
                JFileChooser fileChooser = new JFileChooser();//  Create a file selector 
                FileFilter filter = new FileNameExtensionFilter(
                        " image file (JPG/GIF/BMP)", "JPG", "JPEG", "GIF", "BMP");//  Create filters 
                fileChooser.setFileFilter(filter);//  catalog filter 
                int flag = fileChooser.showOpenDialog(null);//  Show open dialog 
                if (flag == JFileChooser.APPROVE_OPTION) {
    
                    imgFile = fileChooser.getSelectedFile(); //  Get the of the selected picture File object 
                }
                if (imgFile != null) {
    
                    tf_path.setText(imgFile.getAbsolutePath());//  Image full path 
                    try {
    
                        sendImg = ImageIO.read(imgFile);//  structure BufferedImage object 
                    } catch (IOException ex) {
    
                        ex.printStackTrace();
                    }
                }
                sendImagePanel.repaint();//  call paint() Method 
            }
        });
        button.setText(" Select Picture ");
        panel.add(button);

        final JButton button_1 = new JButton();
        button_1.addActionListener(new ActionListener() {
    
            public void actionPerformed(final ActionEvent e) {
    
                try {
    
                    DataInputStream inStream = null;//  Define data input stream objects 
                    if (imgFile != null) {
    
                        lengths = imgFile.length();//  Get the size of the selected picture 
                        inStream = new DataInputStream(new FileInputStream(
                                imgFile));//  Create an input stream object 
                    } else {
    
                        JOptionPane.showMessageDialog(null, " No picture file has been selected .");
                        return;
                    }
                    out.writeLong(lengths);//  Write the size of the file to the output stream 
                    byte[] bt = new byte[(int) lengths];//  Create an array of bytes 
                    int len = -1;
                    while ((len = inStream.read(bt)) != -1) {
    //  Read image file into byte array 
                        out.write(bt);//  Write byte array to output stream 
                    }
                } catch (IOException e1) {
    
                    e1.printStackTrace();
                }
            }
        });
        button_1.setText(" Hair   send ");
        panel.add(button_1);

        final JPanel panel_1 = new JPanel();
        panel_1.setLayout(new BorderLayout());
        getContentPane().add(panel_1, BorderLayout.CENTER);

        final JPanel panel_2 = new JPanel();
        panel_2.setLayout(new GridLayout(1, 0));
        panel_1.add(panel_2, BorderLayout.NORTH);

        final JLabel label_1 = new JLabel();
        label_1.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
        label_1.setText(" The picture selected by the client to send ");
        panel_2.add(label_1);

        final JLabel label_2 = new JLabel();
        label_2.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
        label_2.setText(" Received the picture sent by the server  ");
        panel_2.add(label_2);

        final JPanel imgPanel = new JPanel();
        sendImagePanel = new SendImagePanel();
        receiveImagePanel = new ReceiveImagePanel();
        imgPanel.add(sendImagePanel);
        imgPanel.add(receiveImagePanel);
        final GridLayout gridLayout = new GridLayout(1, 0);
        gridLayout.setVgap(6);
        imgPanel.setLayout(gridLayout);
        panel_1.add(imgPanel, BorderLayout.CENTER);
        //
    }

    //  Create panel class 
    class SendImagePanel extends JPanel {
    
        public void paint(Graphics g) {
    
            if (sendImg != null) {
    
                g.clearRect(0, 0, this.getWidth(), this.getHeight());//  Clear the contents of the drawing context 
                g.drawImage(sendImg, 0, 0, this.getWidth(), this.getHeight(),
                        this);//  Draw a picture of the specified size 
            }
        }
    }

    //  Create panel class 
    class ReceiveImagePanel extends JPanel {
    
        public void paint(Graphics g) {
    
            if (receiveImg != null) {
    
                g.clearRect(0, 0, this.getWidth(), this.getHeight());//  Clear the contents of the drawing context 
                g.drawImage(receiveImg, 0, 0, this.getWidth(),
                        this.getHeight(), this);//  Draw a picture of the specified size 
            }
        }
    }
}


Server startup

 Pictured

The client starts

 Pictured

The client sends pictures to the server

 Pictured

The server receives the picture

 Pictured

The server sends pictures to the client

 Pictured

The client received the picture

 Pictured

Four 、 Recommendation column

《JAVA From zero to one 》

《JAVA Building foundation 100 example 》

5、 ... and 、 Sample source code download

Pay attention to the official account below. , Restoration and foundation construction + Title Number

Building foundation 94

版权声明
本文为[Phyllostachys pubescens]所创,转载请带上原文链接,感谢
https://cdmana.com/2022/174/202206231836178659.html

Scroll to Top