Original Post
Hi, I was wondering if threads created inside an object with the same object as a runnable parameter can access the variable instances inside the object. I'm getting a NullPointerException when I try to read from the stream wrapper I'm using, and I think it's because the stream is not set? Here's the code (everything is happening inside the RevolutionConnection class): Any help would be appreciated. [Edited by - yukit0 on September 15, 2005 4:23:22 PM]
PrintWriter out; // The PrintWriter wrapped around the output stream of the socket
TextReader in; // The TextReader wrapped around the input stream of the socket
Socket connection; // The socket that is connected to the server
Game game; // The game that created this connection, used for handling received data
boolean running; // If set to false, the thread waiting for incoming data will exit
/*
Creates a RevolutionConnection object
*/
public RevolutionConnection(String server, int port, Game g) throws Exception {
if(port < 0 || port > 65535) {
throw new Exception("The port number must be an integer between 0 and 65535");
} else {
try {
connection = new Socket(server, port);
connection.setSoTimeout(30000);
} catch (Exception e) {
reportError("Error while trying to connect to " + server + ":" + e.toString());
throw new Exception("Could not connect to server. Please read the error log for more information.");
}
try {
out = new PrintWriter(connection.getOutputStream());
in = new TextReader(connection.getInputStream());
} catch (Exception e) {
reportError("Error while getting the I/O streams for communicating with the server: " + e.toString());
connection = null;
throw new Exception("Could not connect to server. Please read the error log for more information");
}
game = g;
running = true;
Thread runner = new Thread(this);
runner.start();
}
}
/*
This is run by the thread that reads data from the server.
*/
public void run() {
boolean error = false;
while(running) {
try {
String messageReceived = in.getln(); // Can I use the "in" I set up in the constructor here?
game.processCommand(messageReceived);
} catch (Exception e) {
reportError("Error while reading data from the server: " + e.toString());
game.notify(e);
error = true;
break;
}
}
if (!error) {
sendData("QUIT");
try { connection.close(); } catch (IOException e) { reportError("Connection could not be closed."); }
}
}