2012-11-25 91 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