So I have tried using my code with DataInputStream
and BufferedReader
to send a String from a Client to a Server and have looked up resources all over the Internet for a solution to this. I am using a method that reads in a String from Client and it ALWAYS shows a NullPointerException every time. Here is a copy of the code on the Server side:
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());
}
}
}
I commented in the code where the stacktrace occurs and have done a lot of my own troubleshooting but can't seem to get past the line that creates getGuessFromClient. I'm sure this is a trivial solution but my research has come up empty handed. Does anyone have any suggestions?
By the way, here is the 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)