DataOutputStream不断给出空指针异常

DataOutputStream不断给出空指针异常

所以我尝试将我的代码与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的那一行。我确定这是一个简单的解决方案,但是我的研究空手而归。有没有人有什么建议?

顺便说一下,这是堆栈跟踪:

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)

最佳答案

代替

Socket client = serverSocket.accept();


使用:

client = serverSocket.accept();


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

关于java - DataOutputStream不断给出空指针异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32732162/

10-12 20:46