2012-11-25 118 views
0

我做了一個程序,從手機(Java ME)發送消息「測試」到服務器。但是在嘗試調用服務器端的closeCrap()方法時出現錯誤。服務器端Java錯誤

錯誤日誌:

Exception in thread "main" java.lang.NullPointerException
at server.closeCrap(server.java:106)
at server.startRunning(server.java:55)
at pagr.main(pagr.java:7)

server.java

import java.io.*; 
import java.net.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
public class server extends JFrame{ 
    private static final long serialVersionUID = 1L; 
    private JTextField userText; 
    private JTextArea chatWindow; 
    private ObjectOutputStream output; 
    private ObjectInputStream input; 
    private ServerSocket server; 
    private Socket connection; 
    // constructor 
    public server(){ 
    super("CP Chat"); 
    userText = new JTextField(); 
    userText.setEditable(false); 
    userText.addActionListener(
     new ActionListener(){ 
     public void actionPerformed(ActionEvent event){ 
      sendMessage(event.getActionCommand()); 
      // nusius teksta ivesta 
      userText.setText(""); 
     } 
     } 
    ); 
    add(userText,BorderLayout.NORTH); 
    chatWindow = new JTextArea(); 
    chatWindow.setEditable(false); 
    add(new JScrollPane(chatWindow)); 
    setSize(300,150); 
    setVisible(true); 
    } 
    // set up and run a server 
    public void startRunning(){ 
    try{ 
     // 1 arg - jungiasi prie port (gali buti betkoks) 
     //2 - backLog (kiek zmoniu gali prisijungti prie port) 
     server = new ServerSocket(6789,100); 
     while(true){ 
     try{ 
      waitForConnection(); 
      setupStreams(); 
      whileChatting(); 
     }catch(EOFException exc){ // end of stream 
      showMessage("\n Server ended the connection!"); 
     }finally{ 
      closeCrap(); 
     } 
     } 
    }catch(IOException ex){ 
     ex.printStackTrace(); 
    } 
    } 
    // wait for connection, then display connection info 
    private void waitForConnection() throws IOException{ 
    showMessage("Waiting for someone to connect... \n"); 
    connection = server.accept(); 
    showMessage("Now connected to " + connection.getInetAddress().getHostName()); 
    } 
    // get stream to send and receive data 
    private void setupStreams() throws IOException{ 
    //creating path way to connect to another computer. 
    output = new ObjectOutputStream(connection.getOutputStream()); 
    // flushes any left overs to the other pc while sending messages 
    output.flush(); 
    input = new ObjectInputStream(connection.getInputStream()); 
    showMessage("\n Streams are now setup!\n"); 
    } 
    //during the chat conversation 
    private void whileChatting() throws IOException{ 
    String message = "You are now connected!"; 
    sendMessage(message); 
    ableToType(true); 
    do{ 
     try{ 
     // gauna atsiunciama zinute 
     message = (String) input.readObject(); 
     showMessage("\n" + message); 
     }catch(ClassNotFoundException notFound){ 
     showMessage("\n idk wtf that user send!"); 
     } 
    }while(!message.equals("CLIENT - END")); 
    } 
    //close Streams and Sockets after youre done chatting 
    private void closeCrap(){ 
    showMessage("\n Closing connection... \n"); 
    ableToType(false); 
    try{ 
     output.close(); 
     input.close(); 
     connection.close(); 
    }catch(IOException except){ 
     except.printStackTrace(); 
    } 
    } 
    private void sendMessage(String message){ 
    try{ 
     // sends a message to client 
     output.writeObject("SERVER - " + message); 
     // if something is left - flush those bytes to the client. 
     output.flush(); 
     showMessage("\n SERVER - " + message); 
    }catch(IOException e){ 
     chatWindow.append("\n ERROR: dude i cant send that message"); 
    } 
    } 
    // updates chat window 
    private void showMessage(final String text){ 
    // creates a thread that will update a part of GUI 
    SwingUtilities.invokeLater(
     new Runnable(){ 
     public void run(){ 
      //add message to the end of the document 
      //and it updates the chat window 
      chatWindow.append(text); 
     } 
     } 
    ); 
    } 
    // let the user type something in the text field 
    // final type - cant be modified 
    private void ableToType(final boolean tof){ 
    SwingUtilities.invokeLater(
     new Runnable(){ 
     public void run(){ 
      userText.setEditable(tof); 
     } 
     } 
    ); 
    } 
} 

play.java(手機)

import java.util.Random; 
import java.io.*; 
import javax.microedition.io.*; 
import javax.microedition.lcdui.Graphics; 
import javax.microedition.lcdui.Image; 
import javax.microedition.lcdui.game.GameCanvas; 
import javax.microedition.lcdui.game.Sprite; 
public class play extends GameCanvas { 
    StreamConnection connection; 
    PrintStream output; 
    InputStream in; 
    public play(){ 
    super(false); 
    setFullScreenMode(true); 
    } 
    public void start(){ 
    try{ 
     connection(); 
     setupStreams(); 
    }catch(EOFException ex){ 
    }catch(IOException exc){ 
     exc.printStackTrace(); 
    }finally{ 
     closeCrapi(); 
    } 
    } 
    private void connection() throws IOException{ 
    StreamConnection connection = (StreamConnection)Connector.open("socket://127.0.0.1:6789"); 
    in = connection.openInputStream(); 
    } 
    private void setupStreams() throws IOException{ 
    PrintStream output = new PrintStream(connection.openOutputStream()); 
    output.println("Test"); 
    output.flush(); 
    } 
    private void closeCrapi(){ 
    try{ 
     output.close(); 
     in.close(); 
     connection.close(); 
    }catch(IOException ex){} 
    } 
} 

編輯:我已經改變了Endox哪些用戶告訴我,我有一個錯誤:

java.net.SocketException: Connection reset by peer: socket write error 
    at java.net.SocketOutputStream.socketWrite0(Native Method) 
    at java.net.SocketOutputStream.socketWrite(Unknown Source) 
    at java.net.SocketOutputStream.write(Unknown Source) 
    at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source) 
    at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown Source) 
    at java.io.ObjectOutputStream.<init>(Unknown Source) 
    at server.setupStreams(server.java:75) 
    at server.startRunning(server.java:50) 
    at pagr.main(pagr.java:7) 
Exception in thread "main" java.lang.NullPointerException 
    at server.closeCrap(server.java:107) 
    at server.startRunning(server.java:56) 
    at pagr.main(pagr.java:7) 

EDIT2我將if語句添加到close crap方法中:在關閉輸出之前,它檢查此對象是否爲null。新的錯誤:

java.net.SocketException: Software caused connection abort: recv failed 
    at java.net.SocketInputStream.socketRead0(Native Method) 
    at java.net.SocketInputStream.read(Unknown Source) 
    at java.net.SocketInputStream.read(Unknown Source) 
    at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source) 
    at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source) 
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source) 
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source) 
    at java.io.ObjectInputStream.<init>(Unknown Source) 
    at server.setupStreams(server.java:77) 
    at server.startRunning(server.java:50) 
    at pagr.main(pagr.java:7) 
+0

'server.java'中的第106行是什麼? –

+0

似乎你應該調用'setupStreams'初始化 – onon15

+0

其output.close(); – user1494517

回答

1

在這個循環中:

while(true){ 
     try{ 
       waitForConnection(); 
       setupStreams(); 
       whileChatting(); 
     }catch(EOFException exc){ // end of stream 
       showMessage("\n Server ended the connection!"); 
     }finally{ 
       closeCrap(); 
     } 
} 

如果waitForConnection()拋出EOFException你直接去finally塊(演出消息之後)。 setupStreams()沒有改變被調用,從而在此行引起NullPointerException(內closeCrap()):

output.close(); 
+0

當我運行它拋出的服務器:連接到本地,然後立即在closeCrap()方法「關閉連接」 – user1494517

0

問題可能來自setUpStreams方法Server.java來產生。該行

output = new ObjectOutputStream(connection.getOutputStream()); 

根據java spec ObjectOutputStream可能會拋出異常。

public ObjectOutputStream(OutputStream out) 
        throws IOException 

這可能導致您的output爲空。

1

EDIT3:

output = new ObjectOutputStream(connection.getOutputStream()); 

從跟蹤似乎該行扔Socket Exception,但我不知道爲什麼。所以你應該對這部分做些什麼。 NullPointerExceptionSocketException的後果。

EDIT2:server.java更改此部分:

try{ 
    waitForConnection(); 
    setupStreams(); 
    whileChatting(); 
}catch(EOFException exc){ // end of stream 
    showMessage("\n Server ended the connection!"); 
}finally{ 
    closeCrap(); 
} 

要:

try{ 
     waitForConnection(); 
     setupStreams(); 
     whileChatting(); 
    }catch(IOException exc){ // end of stream 
     exc.printStackTrace(); 
     showMessage("\n Server ended the connection!"); 
    }finally{ 
     closeCrap(); 
    } 

並粘貼在這裏堆棧跟蹤,大概我們可以做一個更好的調試。 :)

編輯:這與play.java有關,仍然是一個問題。

NullPointer Exception投擲因爲你定義了兩個本地變量(連接,輸出)在這些方法中:

private void connection() throws IOException{ 
    StreamConnection connection = (StreamConnection)Connector.open("socket://127.0.0.1:6789"); 
    in = connection.openInputStream(); 
    } 
private void setupStreams() throws IOException{ 
    PrintStream output = new PrintStream(connection.openOutputStream()); 
    output.println("Test"); 
    output.flush(); 
} 

並在closeCrapi()方法使用2類構件,其仍然空引用:

public class play extends GameCanvas { 
     StreamConnection connection; 
     PrintStream output; 
     InputStream in; 
... 
private void closeCrapi(){ 
    try{ 
     output.close(); 
     in.close(); 
     connection.close(); 
    }catch(IOException ex){} 
    } 

所以沒關係在connection()setupStreams()方法中發生了什麼,在closeCrapi()方法上你試着調用兩個方法null引用nce(連接,輸出)。

+0

那麼什麼是stackTrace? – Endox

+0

我把它發佈在主要問題上。我像你說的那樣改變了輸出和連接 – user1494517