Java 使用Socket发送文件的图形化组件,socket图形化,Socket文件发送的图
分享于 点击 49061 次 点评:258
Java 使用Socket发送文件的图形化组件,socket图形化,Socket文件发送的图
Socket文件发送的图形化组件
FileSender.java
package filetransformer;import java.io.*;import java.net.*;public class FileSender extends Thread { private DataOutputStream os = null; private DataInputStream is = null; Socket socket = null; private ServerSocket ss = null; private String filePath = null; private MainJFrame frame; private int port; public FileSender() { } public FileSender(String filePath, int port, MainJFrame frame) { this.filePath = filePath; this.port = port; this.frame = frame; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } @Override public void run() { startSend(filePath, port); } public void startSend(String filePath, int port) { try { File file = new File(filePath); ss = new ServerSocket(port); socket = ss.accept(); os = new DataOutputStream(socket.getOutputStream()); os.writeUTF(file.getName()); os.flush(); long passedlen = 0; long len = (long) file.length(); os.writeLong(len); os.flush(); is = new DataInputStream(new BufferedInputStream( new FileInputStream(filePath))); int bufferSize = 10240; byte[] buf = new byte[bufferSize]; while (true) { int read = 0; if (is != null) { read = is.read(buf); passedlen += read; } if (read == -1) { frame.updateProgressInfo(frame.getFileSendProgressBar(), len, len, frame.getFileSendInfo()); frame.afterSendFile(); break; } //int percent = (int) (passedlen * 100 / len); frame.updateProgressInfo(frame.getFileSendProgressBar(), len, passedlen, frame.getFileSendInfo()); os.write(buf, 0, read); } os.flush(); } catch (IOException e) { e.printStackTrace(); } finally { closeSend(); } } public void closeSend() { try { if (os != null) { os.close(); } } catch (IOException e) { } try { if (is != null) { is.close(); } } catch (IOException e) { } try { if (socket != null) { socket.close(); } } catch (IOException e) { } try { if (ss != null) { ss.close(); } } catch (IOException e) { } } public ServerSocket getSocket() { return ss; } public static void main(String[] args) { new FileSender().startSend(args[0], 8821); }}
MainJFrame.java
package filetransformer;import javax.swing.*;import java.awt.event.*;import java.io.*;import java.util.regex.*;public class MainJFrame extends JFrame { private static final long serialVersionUID = 1L; public MainJFrame() { initComponents(); jPanel1.setBorder(BorderFactory.createTitledBorder("文件发送")); } private void initComponents() { jCheckBoxMenuItem1 = new JCheckBoxMenuItem(); jPanel1 = new JPanel(); fileNameTxt = new JTextField(); sendButton = new JButton(); fileBrowser = new JButton(); jLabel2 = new JLabel(); portTextField = new JTextField(); fileSendProgressBar = new JProgressBar(); fileSendInfo = new JLabel(); cancleSendButton = new JButton(); cancleSendButton.setEnabled(false); fileSavedNameTxt = new JTextField(); jCheckBoxMenuItem1.setSelected(true); jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setTitle("局域网传文件"); setPreferredSize(new java.awt.Dimension(560, 460)); sendButton.setText("发送文件"); sendButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sendButtonActionPerformed(evt); } }); fileBrowser.setText("浏览"); fileBrowser.setActionCommand(""); fileBrowser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fileBrowserActionPerformed(evt); } }); jLabel2.setText("端口"); portTextField.setText("8821"); fileSendProgressBar.setToolTipText("发送文件进度"); cancleSendButton.setText("取消"); cancleSendButton.setEnabled(false); cancleSendButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancleSendButtonActionPerformed(evt); } }); GroupLayout jPanel1Layout = new GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout .setHorizontalGroup(jPanel1Layout .createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup( GroupLayout.Alignment.TRAILING, jPanel1Layout .createSequentialGroup() .addGroup( jPanel1Layout .createParallelGroup( GroupLayout.Alignment.TRAILING) .addGroup( jPanel1Layout .createSequentialGroup() .addContainerGap() .addGroup( jPanel1Layout .createParallelGroup( GroupLayout.Alignment.TRAILING) .addGroup( jPanel1Layout .createSequentialGroup() .addComponent( fileNameTxt) .addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED) .addComponent( fileBrowser) .addGap(18, 18, 18) .addComponent( jLabel2) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED) .addComponent( portTextField, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE)) .addGroup( jPanel1Layout .createSequentialGroup() .addComponent( fileSendInfo, GroupLayout.PREFERRED_SIZE, 295, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED) .addComponent( sendButton, GroupLayout.PREFERRED_SIZE, 81, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED) .addComponent( cancleSendButton, GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)))) .addComponent( fileSendProgressBar, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(22, 22, 22))); jPanel1Layout .setVerticalGroup(jPanel1Layout .createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup( jPanel1Layout .createSequentialGroup() .addGap(19, 19, 19) .addGroup( jPanel1Layout .createParallelGroup( GroupLayout.Alignment.LEADING, false) .addGroup( jPanel1Layout .createParallelGroup( GroupLayout.Alignment.BASELINE) .addComponent( jLabel2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( fileBrowser, GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE)) .addComponent( portTextField) .addComponent( fileNameTxt)) .addGap(18, 18, 18) .addGroup( jPanel1Layout .createParallelGroup( GroupLayout.Alignment.LEADING) .addComponent( fileSendInfo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup( jPanel1Layout .createParallelGroup( GroupLayout.Alignment.BASELINE) .addComponent( sendButton, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE) .addComponent( cancleSendButton, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE))) .addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(fileSendProgressBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(19, 19, 19))); jPanel1Layout.linkSize(SwingConstants.VERTICAL, new java.awt.Component[] { fileBrowser, jLabel2, portTextField, sendButton }); fileSavedNameTxt.setText("D:\\"); GroupLayout layout = new GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup() .addContainerGap() .addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING) .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))); layout.setVerticalGroup(layout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED) .addContainerGap(31, Short.MAX_VALUE))); pack(); }// </editor-fold>//GEN-END:initComponents private void sendButtonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_sendButtonActionPerformed // TODO add your handling code here: String fileName = fileNameTxt.getText().trim(); if (fileName.equals("") || !new File(fileName).exists()) JOptionPane.showMessageDialog(this, "文件不存在!"); else { String port = portTextField.getText().trim(); int portnum; if (isNumeric(port) && (portnum = Integer.parseInt(port)) > 1024 && portnum < 65535) { updateProgressInfo(fileSendProgressBar, 1, 0, null); updateLabelInfo(fileSendInfo, "开始发送文件"); sendButton.setEnabled(false); cancleSendButton.setEnabled(true); fileSender = new FileSender(fileName, portnum, this); fileSender.start(); } else JOptionPane.showMessageDialog(this, "端口必须是1025~65534中的整数!"); } }// GEN-LAST:event_sendButtonActionPerformed public boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); return isNum.matches(); } private void fileBrowserActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_fileBrowserActionPerformed // TODO add your handling code here: showDialog(fileNameTxt, JFileChooser.FILES_ONLY); }// GEN-LAST:event_fileBrowserActionPerformed private void cancleSendButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cancleSendButtonActionPerformed if (fileSender != null) fileSender.closeSend(); fileSender = null; ((JButton) evt.getSource()).setEnabled(false); sendButton.setEnabled(true); fileSendProgressBar.setValue(0); updateLabelInfo(fileSendInfo, "文件发送取消"); }// GEN-LAST:event_cancleSendButtonActionPerformed public static void main(String args[]) { try { for (UIManager.LookAndFeelInfo info : UIManager .getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private JButton cancleSendButton; private JButton fileBrowser; private JTextField fileNameTxt; private JTextField fileSavedNameTxt; private JLabel fileSendInfo; private JProgressBar fileSendProgressBar; private JCheckBoxMenuItem jCheckBoxMenuItem1; private JLabel jLabel2; private JPanel jPanel1; private JTextField portTextField; private JButton sendButton; // End of variables declaration//GEN-END:variables private JFileChooser fDialog; FileSender fileSender; public JLabel getFileSendInfo() { return fileSendInfo; } public JProgressBar getFileSendProgressBar() { return fileSendProgressBar; } protected void showDialog(JTextField updateTxField, int selectMode) { fDialog = new JFileChooser(); fDialog.setFileSelectionMode(selectMode); int result = fDialog.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { String fname = fDialog.getSelectedFile().getAbsolutePath(); updateTxField.setText(fname); } } void afterSendFile() { sendButton.setEnabled(true); fileSender = null; cancleSendButton.setEnabled(false); } void updateLabelInfo(JLabel infoLabel, String msg) { infoLabel.setText(msg); } void updateProgressInfo(JProgressBar progressBar, long len, long passedlen, JLabel infoLabel) { int percent = (int) (passedlen * 100 / len); progressBar.setValue(percent); if (null != infoLabel) { String msg = "已发送:" + (passedlen / 1024) + "KB/" + (len / 1024) + "KB"; if (len == passedlen) msg = "文件发送完成!"; infoLabel.setText(msg); } }}
用户点评