gpt4 book ai didi

java - DataOutputStream 不断给出空指针异常

转载 作者:行者123 更新时间:2023-12-01 18:11:25 27 4
gpt4 key购买 nike

所以我尝试将我的代码与 DataInputStreamBufferedReader 一起使用将字符串从客户端发送到服务器,并在整个互联网上查找资源来解决此问题。我正在使用一种从客户端读取字符串的方法,它每次总是显示 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com