[Java] Java Socket基础 设计界面,在服务器端、客服端间传输图片和文件 →→→→→进入此内容的聊天室

来自 , 2021-01-20, 写在 Java, 查看 163 次.
URL http://www.code666.cn/view/54a367d6
  1. package socket.file;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5. import javax.swing.*;
  6.  
  7. /**
  8.  * 设计界面,在服务器端、客服端间传输图片和文件
  9.  *
  10.  * @author JH
  11.  * @date 2014-9-27
  12.  */
  13.  
  14.  
  15. public class Server {
  16.  
  17.         private SocketFrame socketFrame;
  18.  
  19.         private final int port = 5674;
  20.         private Socket socket;
  21.  
  22.         public Server() {
  23.  
  24.                 try {
  25.                         ServerSocket server = new ServerSocket(port);
  26.                         socketFrame = new SocketFrame();
  27.                         socketFrame.setTitle("Server");
  28.                        
  29.                         while (true) {
  30.  
  31.                                 socket = server.accept();
  32.                                 System.out.println("Server : new socket");
  33.                                 socketFrame.setSocket(socket);
  34.                                 new Thread(Server.this::run).start();
  35.  
  36.                         }
  37.  
  38.                 } catch (IOException e) {
  39.                         System.out.println("Error Server : " + e);
  40.                 }
  41.  
  42.         }
  43.  
  44.         private void run() {
  45.                 while (true) {
  46.                         socketFrame.receive();
  47.                 }
  48.         }
  49.  
  50.         public static void main(String[] args) {
  51.                 try {
  52.                         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  53.                         JFrame.setDefaultLookAndFeelDecorated(true);
  54.                         JDialog.setDefaultLookAndFeelDecorated(true);
  55.                 } catch (ClassNotFoundException | InstantiationException
  56.                                 | IllegalAccessException | UnsupportedLookAndFeelException e) {
  57.                         e.printStackTrace();
  58.                 }
  59.                
  60.                 new Server();
  61.         }
  62.  
  63. }
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. package socket.file;
  71.  
  72. import java.io.*;
  73. import java.net.*;
  74. import javax.swing.*;
  75. import java.util.StringTokenizer;
  76.  
  77. public class Client {
  78.  
  79.         private final int port = 5674;
  80.         private String host = "";
  81.  
  82.         private SocketFrame socketFrame;
  83.  
  84.         public Client() {
  85.  
  86.                 try {
  87.  
  88.                         Socket client = new Socket(host, port);
  89.  
  90.                         client.setSoTimeout(100 * 1000);// 最迟响应时间
  91.                         socketFrame = new SocketFrame();
  92.                         socketFrame.setSocket(client);
  93.                         socketFrame.setTitle("Client");
  94.                         run();
  95.  
  96.                 } catch (IOException e) {
  97.                         System.out.println("Error Server : " + e);
  98.                 }
  99.  
  100.         }
  101.  
  102.         private void run() {
  103.                 while (true) {
  104.  
  105.                         socketFrame.receive();
  106.                 }
  107.         }
  108.  
  109.         private void getHost() {
  110.                 while (true) {
  111.  
  112.                         host = JOptionPane
  113.                                         .showInputDialog("Enter Server IP : eg. 10.110.124.54");
  114.  
  115.                         StringTokenizer token = new StringTokenizer(host, ".");
  116.                         try {
  117.  
  118.                                 while (token.hasMoreTokens()) {
  119.                                         Integer.valueOf(token.nextToken());
  120.                                 }
  121.  
  122.                         } catch (Exception e) {
  123.                                 JOptionPane.showMessageDialog(null, "Formal Error");
  124.                                 continue;
  125.                         }
  126.                         break;
  127.                 }
  128.         }
  129.  
  130.         public static void main(String[] args) {
  131.  
  132.                 try {
  133.                         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  134.                         JFrame.setDefaultLookAndFeelDecorated(true);
  135.                         JDialog.setDefaultLookAndFeelDecorated(true);
  136.                 } catch (ClassNotFoundException | InstantiationException
  137.                                 | IllegalAccessException | UnsupportedLookAndFeelException e) {
  138.                         e.printStackTrace();
  139.                 }
  140.  
  141.                 new Client();
  142.         }
  143.  
  144. }
  145.  
  146.  
  147.  
  148.  
  149.  
  150.  
  151. package socket.file;
  152.  
  153. import java.io.*;
  154. import java.net.*;
  155. import java.awt.*;
  156. import java.awt.event.*;
  157.  
  158. import javax.swing.*;
  159. import javax.swing.text.BadLocationException;
  160.  
  161.  
  162. public class SocketFrame extends JFrame {
  163.  
  164.         private final int WIDTH = 480;
  165.         private final int HEIGHT = 315;
  166.  
  167.         private JTextArea textArea;
  168.         private JFileChooser chooser;
  169.         private JButton sendFile;
  170.         private JButton sendMsg;
  171.  
  172.         private DataOutputStream out;
  173.         private DataInputStream in;
  174.  
  175.         public SocketFrame() {
  176.  
  177.                 setSize(WIDTH, HEIGHT);
  178.  
  179.                 Dimension dime = getToolkit().getScreenSize();
  180.                 setLocation((dime.width - WIDTH) / 2, (dime.height - HEIGHT) / 2);
  181.  
  182.                 createPanel();
  183.  
  184.                 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  185.                 setVisible(true);
  186.         }
  187.  
  188.         private void createPanel() {
  189.  
  190.                 Container contentPane = getContentPane();
  191.                 JPanel buttonPanel = new JPanel();
  192.  
  193.                 textArea = new JTextArea();
  194.                 chooser = new JFileChooser();
  195.  
  196.                 JScrollPane scrollPane = new JScrollPane(textArea);
  197.  
  198.                 sendFile = new JButton("Send File");
  199.                 sendFile.addActionListener(e -> sendFile());
  200.  
  201.                 sendMsg = new JButton("Send Msg");
  202.                 sendMsg.addActionListener(e -> sendMsg());
  203.  
  204.                 buttonPanel.add(sendFile);
  205.                 buttonPanel.add(sendMsg);
  206.  
  207.                 contentPane.add(scrollPane, BorderLayout.CENTER);
  208.                 contentPane.add(buttonPanel, BorderLayout.SOUTH);
  209.  
  210.                 addWindowListener(new WindowAdapter() {
  211.                         public void windowClosing(WindowEvent e) {
  212.  
  213.                         }
  214.                 });
  215.         }
  216.  
  217.         // 发送文件
  218.  
  219.         private void sendFile() {
  220.  
  221.                 int option = chooser.showOpenDialog(this);
  222.                 if (option != JFileChooser.APPROVE_OPTION)
  223.                         return;
  224.  
  225.                 File file = chooser.getSelectedFile();
  226.  
  227.                 long length = file.length();
  228.  
  229.                 textArea.append("开始发送文件 : " + file.getName() + "\n");
  230.  
  231.                 try {
  232.                         // 发送文件名标记
  233.                         out.writeUTF(file.getName());
  234.  
  235.                         // 发送文件长度标记
  236.                         out.writeLong(file.length());
  237.  
  238.                         // 开启此文件的输入流
  239.                         DataInputStream input = new DataInputStream(new FileInputStream(
  240.                                         file));
  241.                         byte[] bytes = new byte[1024];
  242.                         int len = 0;
  243.                         int passedLen = 0;
  244.  
  245.                         while ((len = input.read(bytes)) != -1) {
  246.                                 out.write(bytes, 0, len);
  247.                                 passedLen += len;
  248.  
  249.                                 textArea.append("文件已传送 : " + (passedLen * 100 / length) + "%\n");
  250.  
  251.                                 out.flush();
  252.  
  253.                         }
  254.                         out.flush();
  255.  
  256.                         input.close();
  257.  
  258.                         textArea.append("发送完成 : " + file.getName() + "\n");
  259.                        
  260.                         textArea.setCaretPosition(textArea.getLineStartOffset(textArea
  261.                                         .getLineCount() - 1));
  262.  
  263.                 } catch (IOException | BadLocationException e) {
  264.  
  265.                         System.out.println("From Send() : " + e);
  266.                 }
  267.  
  268.         }
  269.  
  270.         // 发送消息
  271.         private void sendMsg() {
  272.                 String msg = JOptionPane.showInputDialog("Send Message:");
  273.                 if (msg.length() == 0)
  274.                         return;
  275.                 try {
  276.                         // 发送消息的标记
  277.                         out.writeUTF("Message");
  278.                         out.writeUTF(msg);
  279.  
  280.                         out.flush();
  281.                 } catch (IOException e) {
  282.                         e.printStackTrace();
  283.                 }
  284.         }
  285.  
  286.         // 接收 分为 消息和文件
  287.         public void receive() {
  288.  
  289.                 try {
  290.                         // 类型标记
  291.                         String InforType = in.readUTF();
  292.  
  293.                         switch (InforType) {
  294.                         case "Message":
  295.                                 String msg = in.readUTF();
  296.                                 textArea.append(msg + "\n");
  297.                                 break;
  298.                         default:
  299.                                 // 打开个对话框,获取文件保存路径
  300.                                 chooser.setSelectedFile(new File(InforType));
  301.                                 int option = chooser.showSaveDialog(this);
  302.  
  303.                                 if (option != JFileChooser.APPROVE_OPTION)
  304.                                         return;
  305.  
  306.                                 String path = chooser.getSelectedFile().getAbsolutePath();
  307.  
  308.                                 textArea.append("开始接收文件 : " + InforType + "\n");
  309.  
  310.                                 int fileLength = (int) in.readLong();
  311.                                 byte[] buf = new byte[fileLength];
  312.                                 StringBuffer BufferString = new StringBuffer();
  313.  
  314.                                 // output-开启文件的输出流
  315.                                 FileOutputStream output = new FileOutputStream(new File(path));
  316.  
  317.                                 int len = 0;// 一次成功读到的字节
  318.                                 int passedLen = 0;// 目前已读到的字节
  319.                                 while (passedLen < fileLength) {
  320.  
  321.                                         len = in.read(buf, passedLen, fileLength - passedLen);
  322.                                         if (len > 0) {
  323.                                                 passedLen += len;
  324.                                         } else
  325.                                                 break;
  326.  
  327.                                         textArea.append("文件已接收 : " + (passedLen * 100 / fileLength)
  328.                                                         + "%\n");
  329.  
  330.                                         BufferString.append("" + new String(buf, 0, len) + "\n");
  331.                                 }
  332.                                 output.write(buf);
  333.                                 output.flush();
  334.  
  335.                                 output.close();
  336.                                 textArea.append("接收完成,文件存为 : " + path + "\n");
  337.  
  338.                                
  339.  
  340.                                 // 如果是文本文件 打印到文本区里
  341.                                 InforType = InforType.toLowerCase();
  342.                                 if (InforType.endsWith(".txt") || InforType.endsWith(".html")
  343.                                                 || InforType.endsWith(".htm")
  344.                                                 || InforType.endsWith(".java")
  345.                                                 || InforType.endsWith(".jsp")) {
  346.                                         textArea.append(BufferString.toString() + "\n");
  347.                                 }
  348.  
  349.                                 // 如果是图片 打开个对话框显示
  350.                                 if (InforType.endsWith(".png") || InforType.endsWith(".gif")
  351.                                                 || InforType.endsWith(".jpg")
  352.                                                 || InforType.endsWith(".bmp")
  353.                                                 || InforType.endsWith(".jpeg")) {
  354.                                         new ImageDialog(path);
  355.                                 }
  356.                         }
  357.                         chooser.setSelectedFile(new File("."));;
  358.  
  359.                         // 置光标于最后
  360.                         textArea.setCaretPosition(textArea.getLineStartOffset(textArea
  361.                                         .getLineCount() - 1));
  362.                        
  363.                         setVisible(true);
  364.  
  365.                 } catch (IOException | BadLocationException e) {
  366.                         e.printStackTrace();
  367.                 }
  368.  
  369.         }
  370.  
  371.         public void setSocket(Socket socket) {
  372.                 try {
  373.                         out = new DataOutputStream(new BufferedOutputStream(
  374.                                         socket.getOutputStream()));
  375.                         in = new DataInputStream(new BufferedInputStream(
  376.                                         socket.getInputStream()));
  377.                 } catch (IOException e) {
  378.                         e.printStackTrace();
  379.                 }
  380.         }
  381.  
  382. }
  383.  
  384.  
  385.  
  386. package socket.file;
  387.  
  388. import javax.swing.*;
  389.  
  390. import java.awt.*;
  391. import java.awt.image.BufferedImage;
  392.  
  393. /**
  394.  * 显示图片
  395.  */
  396.  
  397. public class ImageDialog extends JDialog {
  398.  
  399.         private ImageIcon img;
  400.         private int WIDTH = 500;
  401.         private int HEIGHT = 500;
  402.  
  403.         public ImageDialog(String path) {
  404.  
  405.                 img =new ImageIcon(path);
  406.  
  407.                 scaleImage();
  408.                 setTitle(path);
  409.  
  410.                 setVisible(true);
  411.         }
  412.  
  413.         public void paint(Graphics g) {
  414.                 super.paint(g);
  415.                 g.drawImage(img.getImage(), 5,30 , WIDTH, HEIGHT, null);
  416.         }
  417.  
  418.         public void scaleImage() {
  419.                
  420.                 int imgWidth = img.getIconWidth();
  421.                 int imgHeight = img.getIconHeight();
  422.  
  423.                 if (imgWidth >= imgHeight) {
  424.  
  425.                         HEIGHT = (int) Math.round((imgHeight * WIDTH * 1.0 / imgWidth));
  426.  
  427.                 } else {
  428.  
  429.                         WIDTH = (int) Math.round((imgWidth * HEIGHT * 1.0 / imgHeight));
  430.                 }
  431.  
  432.        
  433.                
  434.                 setSize(WIDTH+5, HEIGHT+30);
  435.  
  436.                 System.out.println("scrImg W " + imgWidth + " H " + imgHeight);
  437.                 System.out.println("Scale W " + WIDTH + " H " + HEIGHT);
  438.  
  439.                 /*
  440.                  * JLabel label = new JLabel(); JPanel panel = (JPanel)
  441.                  * getContentPane(); panel.setOpaque(false);
  442.                  *
  443.                  * label.setBounds(0, 0, WIDTH, HEIGHT);
  444.                  *
  445.                  * getLayeredPane().add(label, new Integer(Integer.MIN_VALUE));
  446.                  */
  447.         }
  448. }
  449.  
  450.  
  451.  

回复 "Java Socket基础 设计界面,在服务器端、客服端间传输图片和文件"

这儿你可以回复上面这条便签

captcha