DataOutputStream保持给出空指针异常

时间:2015-09-23 06:06:37

标签: java

所以我尝试在DataInputStreamBufferedReader上使用我的代码 从客户端向服务器发送字符串,并在整个Internet上查找资源以获得解决方案。我正在使用一个从客户端读取字符串的方法,它每次都会显示一个NullPointerException。以下是服务器端代码的副本:

package WOF;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TheBoard {

    private int port;
    Socket client;

    public TheBoard(int port)
    {
        this.port = port;
    }
    public void start() throws IOException 
    {
            System.out.println("Now Determining if guess is correct");

            ServerSocket serverSocket = new ServerSocket(port);

            Socket client = serverSocket.accept();
            sendWelcomeMessage(client); 
    }
    private void sendWelcomeMessage(Socket client) throws IOException
    {
        DataOutputStream out = new DataOutputStream(client.getOutputStream());
        out.writeBytes("Hello, You are now Playing Wheel of Fortune, Command Line Style!!");
    }
    public void getGuess(Socket client) throws IOException
    {
        String userInput;
        DataInputStream getGuessFromClient = new DataInputStream(client.getInputStream()); //NPE Occurs Right on this Line.
        System.out.println(getGuessFromClient);
        userInput = getGuessFromClient.readUTF();
        System.out.println("Guess is: " + userInput);
    }   
    public static void main(String[] args) {

        int portNumber = 9990;
        try 
        {
            TheBoard socketServer = new TheBoard(portNumber);
            socketServer.start();
            socketServer.getGuess(socketServer.client); //This Throws an NPE
        } 
        catch (IOException e)
        {
            System.err.println("UH OH!! Can't Connect.." + e.getMessage());
        }
    }
}

我在堆栈跟踪发生的代码中发表了评论并完成了很多我自己的故障排除,但似乎无法通过创建getGuessFromClient的行。我确信这是一个微不足道的解决方案,但我的研究空手而归。有没有人有任何建议?

顺便说一下,这是stacktrace:

Now Determining if guess is correct
Exception in thread "main" java.lang.NullPointerException
    at WOF.TheBoard.getGuess(TheBoard.java:40)
    at WOF.TheBoard.main(TheBoard.java:52)

2 个答案:

答案 0 :(得分:2)

而不是

Socket client = serverSocket.accept();

使用:

client = serverSocket.accept();

您正在将客户端分配给局部变量,而不是成员变量,因此您在取消引用之前当前没有分配成员变量。

答案 1 :(得分:1)

您已声明"客户"变量两次:

  1. TheBoard class
  2. 内部的start()方法。它只是一个局部变量。
  3. 但是你应该在start()方法中使用相同的实例变量。所以而不是:

    Socket client = serverSocket.accept();
    

    client = serverSocket.accept();
    

    在start()方法中。