java.lang.NullPointerException通过对象输出流发送消息时

时间:2013-01-05 13:14:54

标签: java sockets nullpointerexception awt

我尝试使用对象发送消息。我有一些代码可以创建一个GUI和另一块代码,如果没有连接,它可以创建一个服务器,如果服务器可用,则可以充当客户端。用户通过GUI键入消息,并通过“communicator”作为“消息”对象发送。如果将通信器设置为客户端,则用户可以发送消息,但如果将其设置为服务器则不能发送消息...

如果用户尝试发送包含程序设置为服务器的消息,则会出现以下错误。

线程中的异常“AWT-EventQueue-0”java.lang.NullPointerException

消息不发送

这是我的通讯器代码,底部是应该发送消息的函数

package hunterinstant;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author Chris
 */
public class HunterCom implements Runnable {

    private static String SERVER_IP = "127.0.0.1";
    private static int SERVER_PORT = 5000;
    Scanner scanner = new Scanner(System.in);   //to read text from the console
    Socket socket = null;
    boolean client;
    Conversation window;
    ObjectOutputStream out = null;

    public void initialize(Conversation c, String ip, String port) {
        System.out.println(ip);
        System.out.println(port);
        SERVER_IP = ip;
        SERVER_PORT = Integer.parseInt(port);
        window = c; 
    }



    public void run() {

        try {
            socket = new Socket(SERVER_IP, SERVER_PORT);
            window.addText("Connected to server");
            client = true;
        } catch (Exception ex) {
            window.addText("No Users Online: Waiting for connection");
            client = false;

        }

        if (client == true) {

        ObjectInputStream in = null;
        while (true) {
            try {
                if (out == null) {
                    out = new ObjectOutputStream(socket.getOutputStream());
                }

                //get the reply from the server
                if (in == null) {
                    in = new ObjectInputStream(socket.getInputStream());
                }
                Message message = (Message) in.readObject();

                window.addText(message.getMessage());
                //System.out.println("Server said: " + message.getMessage());

            } catch (Exception ex) {
                window.addText("Error: " + ex);
            }
        }

    } // End Client

        else {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(SERVER_PORT);
            } catch (IOException ex) {
                window.addText("Error occured while creating the server socket");
                return;
            }

            Socket socket = null;
            try {
                //Waits untill a connection is made, and returns that socket
                socket = serverSocket.accept();
            } catch (IOException ex) {
                window.addText("Error occured while accepting the socket");
                return;
            }
            window.addText("Connection created, client IP: " + socket.getInetAddress());
            ObjectInputStream in = null;
            while (true) {
                try {
                    if (in == null) {
                        in = new ObjectInputStream(socket.getInputStream());
                    }

                    Message message = (Message) in.readObject();

                    window.addText(message.getMessage());
                    if (out == null) {
                        out = new ObjectOutputStream(socket.getOutputStream());
                    }
                } catch (Exception ex) {
                    window.addText("Error: " + ex);
                }
            }
        }
    }

//THIS IS THE CODE THAT IS SUPPOSED TO SEND THE MESSAGE
    public void sendMessage(String str) 
    {
        try {
            out.writeObject(new Message(str));
            System.out.println("Hello");
            out.flush();
        } catch (IOException ex) {
            Logger.getLogger(HunterCom.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

这是应该从GUI发送消息的代码

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    comunicator.sendMessage(jTextField1.getText());
    jTextArea2.append(jTextField1.getText());
}

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
    if(evt.getKeyCode()==10) // Has the user pressed enter?
    {
        comunicator.sendMessage(jTextField1.getText());
        jTextArea2.append(jTextField1.getText());
    }
}

对不起,我确信这是一个非常愚蠢的问题...我确定我在做一些非常明显愚蠢的事情,但我只做了几个月的java而且我花了好几个小时试图计算这一个没有欢乐......

2 个答案:

答案 0 :(得分:6)

时间?哦,我的。

首先阅读堆栈跟踪。它告诉您行号和发生NPE的.java源文件。转到该行,查看对象引用,并查看哪一个为null。

NPE易于修复。这通常是因为您对对象初始化做出了错误的假设。您只需要弄清楚如何正确初始化该引用。范围,构造函数 - 你会发现问题。

获得像IntelliJ这样的体面的IDE,并使用调试器逐步完成代码。它需要十分钟 tops ,而不是几小时。

就个人而言,我不愿意为某人调试大量代码。你的不完整,所以无法编译和运行。您没有在您的问题中粘贴堆栈跟踪,因此我无法为您阅读。你几乎没有帮助我们帮助你。

答案 1 :(得分:0)

try: while(true&&socket.isConnected()){
                   .....

有时候

Message message = (Message) in.readObject(); 

在套接字连接之前运行并且它会抛出NPE