0

我制作了一个程序,它从电话(Java ME)向服务器发送“测试”消息。但是在尝试调用closeCrap()服务器端的方法时出现错误。

错误日志:

在 pagr.main(pagr.java:7) 的 server.startRunning(server.java:55)
的 server.closeCrap(server.java:106)的线程“main”java.lang.NullPointerException中的异常


服务器.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 语句:在关闭输出之前,它会检查此对象是否不为空。新错误:

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)
4

3 回答 3

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();
于 2012-11-25T12:08:39.937 回答
1

编辑3:

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

从跟踪看来,那条线扔了一个Socket Exception,但我不知道为什么。所以你应该对这部分做点什么。NullPointerException是 的结果SocketException

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引用(连接,输出)的方法的方法中。

于 2012-11-25T14:49:33.250 回答
0

问题可能是由in 中的setUpStreams方法引起的Server.java。线

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

根据java规范ObjectOutputStream可能会抛出异常。

public ObjectOutputStream(OutputStream out)
                   throws IOException

这可能导致您output为空。

于 2012-11-25T12:49:16.807 回答