簡體   English   中英

Java Socket BufferReader.readline獲取null

[英]Java Socket BufferReader.readline get null

我是Java的新手,我嘗試用TCP Socket編寫一個簡單的客戶端服務器,但是經過幾天的努力我遇到了麻煩,但我無法解決此問題。

我的BufferReader.Readline()為空;

我的服務器代碼:

啟動服務器代碼

public class StartServer {
    ServerSocket server;
    public StartServer(){
        try {
            server = new ServerSocket(4444);
        } catch (Exception e) {
            System.out.println("server can't listen to this port");
        }
         System.out.println("Listening for clients on 4444..."); 
        int id =0;
        while(true)
        {
            try {
                Socket client = server.accept();
                ServerThread svThread = new ServerThread(client, id++);
                svThread.start();
            } catch (Exception e) {
                System.out.println("Error.......");
            }
        }
    }

    public static void main(String[] args) {
        new StartServer();
    }

}

服務器線程:

public class ServerThread extends Thread{
    Socket client;
    int clientID = 0;
    boolean threadRun = true;
    BufferedReader inputFromClient = null;
    PrintWriter outputFromServer = null;

    public ServerThread(Socket socket, int cID) {
        client = socket;
        clientID = cID;
    }


    public void run() {
        try {
            inputFromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
            outputFromServer  = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
            System.out.println("ClientID: " + clientID);

            while(threadRun){
                String textFromClient = inputFromClient.readLine();
                System.out.println("Client ID: " + clientID + " Client says: " + textFromClient);

                if(textFromClient.equals("Quit")){
                    threadRun = false;
                    System.out.println("Stop client Thread from: " + clientID);
                }else{
                    outputFromServer.print(textFromClient);
                    outputFromServer.flush();
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            try {
                inputFromClient.close();
                outputFromServer.close();
                client.close();
                System.out.println("Server Stopped...");
            } catch (Exception e) {
            }
        }
    }




}

我的客戶端使用JFrame調用面板,並使用文本字段和jbutton將消息發送到服務器

但是,當我發送一條消息時,服務器可以接收到該消息並將其打印到命令行,但是它繼續嘗試從客戶端獲取消息(因為它在while循環內),但是接收到null,在這種情況下我不知道

我的客戶代碼:

JFrame代碼:

public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */

    Panel1 p ;
    public NewJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jDesktopPane1 = new javax.swing.JDesktopPane();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(196, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(91, 91, 91))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(83, 83, 83)
                .addComponent(jButton1)
                .addContainerGap(134, Short.MAX_VALUE))
        );

        jPanel1.setBounds(0, 0, 360, 240);
        jDesktopPane1.add(jPanel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 365, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 35, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 35, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        p   = new Panel1();
        jDesktopPane1.removeAll();
        jDesktopPane1.repaint();
        jDesktopPane1.revalidate();
         p.setBounds(0, 0, 840, 558);
        p.setSize(840,558);
        jDesktopPane1.add(p);
        p.show();

    }                                        

    /**
     * @param args the command line arguments
     */
    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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

我的面板代碼:

public class Panel1 extends javax.swing.JPanel {
 Socket s;
 PrintWriter outPut = null;
    /**
     * Creates new form Panel1
     */
    public Panel1() {
        initComponents();
        ConnectServer();
       //sendToServer();
       // receiveFromServer();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */

    public void ConnectServer(){
        try {
             s = new Socket("localhost", 4444);
             System.out.println("Connect to server");
             outPut = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
           //  PrintWriter outPut = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
            //outPut.println("Test cai coi.....");
            //outPut.flush();
        } catch (UnknownHostException ex) {
            Logger.getLogger(Panel1.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Panel1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void receiveFromServer(){
        try {
            BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
            System.out.println(input.readLine());
        } catch (IOException ex) {
            Logger.getLogger(Panel1.class.getName()).log(Level.SEVERE, null, ex);
        }

    }


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

        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(157, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(243, Short.MAX_VALUE))
        );
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       //PrintWriter outPut = null;
        PrintWriter outToServer = null;
         BufferedReader input = null;
        try {
            // TODO add your handling code here:
            outToServer  = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

            String txtFromClient = jTextField1.getText();
           // String clientText = input.readLine();
            System.out.println(txtFromClient);
            outToServer.println(txtFromClient);
            outToServer.flush();

            //





            //outPut.flush();
             //System.out.println(input.readLine());
        } catch (Exception ex) {
            Logger.getLogger(Panel1.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            //outPut.close();
             outToServer.close();
        }


    }                                        

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

和我從服務器的堆棧跟蹤:

Exception in thread "Thread-0" java.lang.NullPointerException
    at testserverclient.ServerThread.run(ServerThread.java:39)

第39行是:

if(textFromClient.equals("Quit"))

處理退出消息的想法很好。 但是您的客戶永遠不會發送這樣的退出消息。 它只是關閉插座。 這導致在套接字的另一端(您的服務器),當您詢問下一行時,BufferedReader返回null。 因此,要解決此問題,請確保您的客戶端編寫了quit-message,這將使服務器在適當的時候關閉套接字並停止從中讀取信息。 並且非常確定的是,如果返回的String為null,則在服務器端添加檢查。

if (textFromClient == null || textFromClient.equals("Quit"))
{
     socket.close();
     break; // Break out of the reading loop.
}

編輯 :這對於客戶端:

if (txtFromClient.equals("Quit"))
{
    outToServer.println("Quit");
    outToServer.flush();
    outToServer.close();
}

確保不要在finally塊中關閉套接字。 僅在發送退出消息時將其關閉。


提示 :您可以在自動刷新模式下構造PrintStream:

PrintStream outToServer = new PrintStream(socket.getOutputStream, true);

啟用自動刷新時,它將在每個print(ln)語句之后刷新。 因此,您不必每次都調用flush()

BufferedReader.readLine()返回null時,這意味着沒有更多數據可讀取。 您在流的盡頭。 (通常使用套接字,這意味着另一端關閉了連接。)

當然, null不是對象, null.equals(anything)將引發異常。

您可以這樣說來避免出現異常

if (textFromClient == null || textFromClient.equals("Quit"))

因為任何一種情況都意味着客戶端已完成,並且應該終止連接。

至於客戶端...關閉套接字給您的流(就像您在jButton1ActionPerformed所做的一樣),也將關閉套接字。 您可能希望將最頂級的流成員字段設置為客戶端中的某個位置,以便可以在兩次調用之間保留它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM