Решить проблему невозможности передачи файлов - PullRequest
0 голосов
/ 01 декабря 2019

Я изучал создание программы чата с учебного сайта и применил все вышеперечисленное в объяснении, но у меня есть проблема - невозможность передачи файлов и изображений между сервером и клиентом. Этот код используется в чате. Я провел много экспериментов, но я не могу решить проблему.

Список сообщений:

public class MessageList extends Thread{
  
   ServerSocket srever;
   int port=1000;
   WritableGUI gui;
       private ObjectOutputStream out;

   public MessageList(WritableGUI gui,int port){
   
       this.port=port;
       this.gui=gui;
       try {
           srever=new ServerSocket(port);
       } catch (IOException e) {
           Logger.getLogger(MessageList.class.getName()).log(Level.SEVERE, null, e);
       }
       
   }
   
   


    
   
   
   @Override
   public void run(){
       Socket clientSocket;
       try {
           while ((clientSocket=srever.accept())!=null) {               
               InputStream is = clientSocket.getInputStream();
              BufferedReader br = new BufferedReader(new InputStreamReader(is));
              String line = br.readLine();
             
              if(line !=null){
                  gui.write(line);
              }
           }
           
       } catch (Exception e) {
                      Logger.getLogger(MessageList.class.getName()).log(Level.SEVERE, null, e);
       }
    
  
   }


}
Сообщение:

public class MessageTransmitter extends Thread{
    
    String message , hostname;
    int port=1000; 
 int filesize=2022386; 
        int bytesRead;
        int currentTot = 0;
    public MessageTransmitter(){
        
    }
    
    public MessageTransmitter(String message ,String hostname,int port ){
        this.message=message;
        this.hostname=hostname;
        this.port=port;
    }
 @Override
 public void run(){
     try {
           Socket s =new Socket(hostname,port);
           s.getOutputStream().write(message.getBytes());
           
           s.close();
          
       } catch (IOException e) {
           Logger.getLogger(MessageTransmitter.class.getName()).log(Level.SEVERE, null, e);
       }
     
 
 }



}

WritableGUI:

public interface WritableGUI  {
    void write(String s);
    
}

Пожалуйста, помогите мне решить эту проблему.

1 Ответ

0 голосов
/ 02 декабря 2019

public class MainScreen extends javax.swing.JFrame implements WritableGUI {

   
    public MainScreen() {
        initComponents();
    }

   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        ip = new javax.swing.JTextField();
        Sender = new javax.swing.JTextField();
        listen = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        chat = new javax.swing.JTextArea();
        mass = new javax.swing.JTextField();
        sendB = new javax.swing.JButton();
        receiver = new javax.swing.JTextField();
        Exit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(208, 204, 202));

        ip.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 13)); // NOI18N
        ip.setText("localhost");
        ip.setToolTipText("");
        ip.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ipActionPerformed(evt);
            }
        });

        Sender.setText("200");

        listen.setBackground(new java.awt.Color(255, 192, 27));
        listen.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 13)); // NOI18N
        listen.setText("Listen");
        listen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listenActionPerformed(evt);
            }
        });

        chat.setColumns(20);
        chat.setRows(5);
        jScrollPane1.setViewportView(chat);

        sendB.setBackground(new java.awt.Color(255, 192, 27));
        sendB.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 13)); // NOI18N
        sendB.setText("send");
        sendB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendBActionPerformed(evt);
            }
        });

        receiver.setText("100");

        Exit.setBackground(new java.awt.Color(255, 192, 27));
        Exit.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 13)); // NOI18N
        Exit.setText("Exit");
        Exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
                    .addComponent(mass, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(Sender)
                    .addComponent(receiver)
                    .addComponent(ip, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                    .addComponent(listen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(Exit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(sendB, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(219, 219, 219)
                        .addComponent(sendB, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Sender, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(receiver, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ip, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(listen, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5)
                        .addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(mass, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    

   MessageList listener;
    private void listenActionPerformed(java.awt.event.ActionEvent evt) {                                       
     listener =new MessageList(this,  Integer.parseInt(Sender.getText()));
    listener.start();
     

    }                                      

    private void sendBActionPerformed(java.awt.event.ActionEvent evt) {                                      
        MessageTransmitter mt = new MessageTransmitter(mass.getText(), ip.getText(), Integer.parseInt(receiver.getText()));
        mt.start();
    
    }                                     

    private void ipActionPerformed(java.awt.event.ActionEvent evt) {                                   
        // TODO add your handling code here:
    }                                  

    private void ExitActionPerformed(java.awt.event.ActionEvent evt) {                                     
            System.exit(0);
    }                                    
  
   
    
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainScreen().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton Exit;
    private javax.swing.JTextField Sender;
    private javax.swing.JTextArea chat;
    private javax.swing.JTextField ip;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton listen;
    private javax.swing.JTextField mass;
    private javax.swing.JTextField receiver;
    private javax.swing.JButton sendB;
    // End of variables declaration                   

    @Override
    public void write(String ss) {
        
        chat.append(ss+System.lineSeparator());
        
        
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...