繁体   English   中英

服务器端Java错误

[英]Server-side Java error

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

错误日志:

线程“main”java.lang.NullPointerException中的异常
在server.closeCrap(server.java:106)
在server.startRunning(server.java:55)
在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)

在这个循环中:

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();

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){}
  }

因此, setupStreams()connection()setupStreams()方法中发生什么,在closeCrapi()方法中,您尝试在两个null引用(连接,输出)上调用方法。

问题可能来自Server.java setUpStreams方法。 这条线

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

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

public ObjectOutputStream(OutputStream out)
                   throws IOException

这可能导致您的output为null。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM