my program keeps throwing nullPointerException at me and I have no idea why. I thought maybe it's because of the bufferedReader but I'm not sure.
String line = reader.readLine();
while (!line.isEmpty()) {
line = repairLine(line);
tree.add(line);
line = reader.readLine();
}
Yes, it is wrapped in try - catch block. It says that the problem is on the while-line. It didn't work with "if (line != null)". I really don't know what could cause that. Thanks you for any help.
The problem seems to be with the following lines of your code :
String line = reader.readLine();
while (!line.isEmpty()) {
}
If there is nothing to read from the file, line will be null. Thus the exception in the while loop. You are trying to call a method on a null reference.
That being said, the traditional way of reading lines from a file is to assign the line read to a variable in the while condition itself (code not tested) :
String line = "";
while ((line=reader.readLine()!=null) && !line.isEmpty()) {
line = repairLine(line);
tree.add(line);
}
I have had this same error and it meant that the socket is closing on the other connected client while it is trying to read on the server.
To add some context, I am running a server and various clients are connecting to it via java sockets. I was having this error on the server side when the client closes the socket.
So to solve the issue I decided to close both server side and client side sockets after every connection. The way I have done this is before client is closed it sends a "quit" message to the server before closing its sockets. When the server reads the "quit" message it will also close its sockets.
For example:
Client side
if(Quit){
if(mySocket != null && !mySocket.isClosed()) {
output.println("quit");
output.flush();
try {
mySocket.close();
} catch (IOException e) {
System.out.println("Close net variables exception - " + e.getMessage());
}
}
}
Server side
String line = input.readLine(); //Thread stops here untill it reads something
if(line.equals("something")){
do_something();
else if(line.equals("quit")){
try {
mySocket.close();
} catch (IOException e) {
System.out.println("Close net variables exception - " + e.getMessage());
}
else{
do_default();
}
Worked for me, hope it helps!
Related
Every line of code is executed -> Event -> Important Java code lines skipped
# Client-Server # AssumeNoCodeOptimization # IDE:Processing (Processing.org by MIT)
There is a Thread "ConnectionHandler" that stays in a loop where it either sends or receives data. Before it receives the first data, every line of code is executed. After that, the program seems to pause at a System.out.println()!?
Then, when more data arrive, certain lines of Java Code are executed again, but the very same System.out.println() - in addition other things - I mentioned before is skipped.
The very problem is actually that a method sendOutput() is skipped. This is what really grinds my gears. Please help.
I am programming in an environment called Processing, developed by the MIT. As far as I know it only wraps more Java code arround your code.
Below the following code snippets I will explain why I think that code optimization by JIT or AOT is not the problem (At the end I guess I will be wrong. I hope the opposite because you can not pass System variables to Processing to suppress optimization)
private void runConnectionHandler() {
final BufferedReader inFromClient = getBufferedReader(socket);
final DataOutputStream dataOutputStream = getDataOutputStream(socket);
while (true) {
getInput(inFromClient);
sendOutput(dataOutputStream);
System.out.println("Cycle ends");
}
}
private void getInput(final BufferedReader input) {
System.out.println("Get");
try {
String clientSentence = null;
if (input.ready()) {
while ((clientSentence = input.readLine()) != null) {
inputQueue.add(new GameData(clientSentence));
System.out.println("Received se: \"" + clientSentence + "\"");
System.out.println("1");
}
System.out.println("2");
}
System.out.println("3");
}
catch (final Exception e) {
e.printStackTrace();
}
}
private void sendOutput(final DataOutputStream dataOutputStream) {
System.out.println("Send");
while (outputQueue.peek() != null) {
try {
String out = outputQueue.poll().toString();
dataOutputStream.writeBytes(out + "\r\n");
dataOutputStream.flush();
System.out.println("Sent \"" + out + "\"");
}
catch (final Exception e) {
e.printStackTrace();
}
}
}
OUTPUT: Before first data:
Having no idea about optimization I would think that it should also come to effect here, but it does not?
...
Get
3
Send
Cycle ends
...
OUTPUT: First data arrive
After the "1" the ouput stops. Why is System.out.println("2"); and so on not executed?! Why does it stop?!?!
...
Get
3
Send
Cycle ends
Get
Received se: "SET PLAY MODE"
1
OUTPUT: Manually sent more data
Gad dayium, I mean where went my System.out.println("Get"); and everything?!
...
Get
Received se: "SET PLAY MODE"
1
Received se: "Hey Ho1"
1
OUTPUT: Server shuts down
When I shut down the other side (Server), every line of code is executed again ?!?! Futhermore neither it stops, nor an execution is thrown (But maybe different issue).
...
Get
3
Send
Cycle ends
...
Also if my concept is deeply broken I would appreciate a lot of hints.
I am currently interfacing a GUI to an UCI chess engine. For this purpose i am creating the engine process using:
try {
process = Runtime.getRuntime().exec(enginePath);
} catch (IOException e) {
System.err.println("ENGINE NOT FOUND");
e.printStackTrace();
}
and i am sure that i am able to open the engine.
When engine is opened, there is no significant stream outputted from engine. In order to initiate communication, I have to send specific commands to the engine. The engine will respond then... Therefore it is working in a command/response approach(not immediately streaming data when opened or talking without spoken to). In order to communicate i have a send message block. In this block write a message to the engine using its outputstream and get input using its standart input stream as in the following send method:
private String sendCommand(String command) {
stdin = new PrintWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errReader = new BufferedReader(newInputStreamReader(process.getErrorStream()));
String answer = "";
stdin.println(command);
stdin.flush();
stdin.close();
try {
String line = "";
while ((line = inputReader.readLine()) != null) {
System.out.println(line);
answer = line;
}
inputReader.close();
} catch (IOException ioe) {
System.err.println("READ ERROR");
ioe.printStackTrace();
}
try {
String line = "";
while ((line = errReader.readLine()) != null) {
System.err.println(line);
}
errReader.close();
} catch (IOException ioe) {
System.err.println("READ ERROR");
ioe.printStackTrace();
}
return answer;
}
By the way the whole engine is working in a single seperate thread other than the main GUI thread. Therefore no overloading for the GUI. However i didnot seperate the stdin stderr and output methods in individual threads since i suppose there will be only stdin and the one that i will write to the engine. For the time being i assume they will not collide.
With these codes i am able to communicate with the engine and i can see the outputs in the console. However due to stdin.close(); i can only use this method once (In the seconds time i have a STREAM CLOSED error). The chess engine is needed to be communicated in command/response approach many times when opened, without restarting the exe in each time. The problem is that if i remove the line : stdin.close(); yes the communication continues, but my console is blocked by this communication. I.e. i cannot println to the console for debugging purposes anymore. Which is very critical because my main debugging weapon is system.out.println. If i do not remove stdin.close(); i have to restart executable each time i want to send message and i do not want that. **The strange part is that i can see the messages coming from the engine in my console due to "System.out.println(line);" line in the send method; however i cannot print anything on the console once the code exits the method. **
EDIT: Actually after this block:
while ((line = inputReader.readLine()) != null) {
System.out.println(line);
answer = line;
}
System.out.println starts not to work.
EDIT: The problem seems not to be with println but any statement after while loop.
Why statements after while loop is not getting executed?
according to this, it seems that since the stream is never closed, "while loop" is stuck(?). Actually when printing inside while loop, at some point(after a stream is finished), the prints stop, which must indicate while loop is finished. Therefore if it is finished, it should continue on the next statements, shouldn't it? Anyway, the messages from the engine had a set of strings at end of each stream; therefore when i encounter one of them i am breaking the while loop.
Note: it is also interesting that : accumulating data as: "receivedString += line"; doesnot work,i.e. data is not accumulated. In order to fix it i luckily made it "receivedString = receivedString + line + "\n""; and it worked.. I dont know why.
You're reading the input until end of stream, so it won't stop reading until end of stream occurs. End of stream means that the peer has closed the connection in this case. That won't happen for a process's output or error stream until the process exits. You'll have to find some other loop termination condition, or else consume the stdout and stderr in separate threads.
I am developing a program that uses sockets and currently I have a function in my code that checks for a heartbeat from the client every second.
private void userLoop() { // checks for incoming data from client
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
try {
socketIn.read(); // check for heartbeat from client
String userInput;
while ((userInput = br.readLine()) != null) {
}
} catch (Exception e) {
ControlPanel.model.removeElement(getUsername());
ControlPanel.append(getUsername() + " has disconnected.");
}
}
}, 1000);
}
When a client closes the game via the X button, shutting off their computer, logging out, whatever it may be, I get the message "'username' has disconnected". This is exactly what I want, however, it only works with the while loop in the code. The while loop essentially does nothing and I have no idea why it doesn't work with out.
If I remove the while loop and I disconnect using my client nothing gets printed out server sided.
String userInput;
while ((userInput = br.readLine()) != null) {
}
The above is essentially the dead code that does nothing but without it my program doesn't work the way it should..
Why is the code needed and how can I remove it and still make my program work correctly?
In this case, your while loop is essentially stalling your program until you no longer receive an input string. It's not dead code; it is just your way of installing a wait.
Otherwise, based on my understanding in the Timer class, it only waits one second, which might be too short of a timespan for what you're waiting to capture.
I fixed my problem by changing everything in the try block with
br.readLine();
There's a saying I've heard about exception handling: "Exceptions should only be used for exceptional situations." A client disconnecting from a server is not exceptional.
Now that I have that off my chest, let's move on. According to this other question,
socket.getInputSteam.read() does not throw when I close the socket from the client
it sounds like the read call won't throw if you're closing things properly on the client side.
The problem is that when the remote socket is closed, read() does not throw an Exception, it just returns -1 to signal the end of the stream.
The following should work without needing to call readLine():
try {
int ret = socketIn.read(); // check for heartbeat from client
if (ret == -1) {
// Remote side closed gracefully
clientDisconnected();
}
} catch (SocketTimeoutException e) {
// Timeout -- handle as required
handleTimeout();
} catch (IOException e) {
// Connection lost due to I/O error
clientDisconnected()
}
Good afternoon everybody!
I'm trying to create a simnple messagging application but I cannot find a solution to a big issue. Exactely there are two, big issues.
Here the code:
#Override
public void run() {
String incoming;
try {
while (true) {
if (!connected)
break;
// READING
if (reader.ready() && (incoming = reader.readLine()) != null) {
notifier.putCommand(incoming, this);
incoming = null;
}
// WRITING
synchronized (messagges) {
for (String message : messagges) {
System.out.println("SENDING MESSAGE TO CLIENT: " + message);
writer.println(message);
}
messagges.clear();
}
writer.println("b");
}
} catch (IOException e) {
MyLogger.log(e);
}
}
Problems:
If I don't every time write junk text to the client (writer.println("b")) I cannot read any message on the BufferedReader, sent from it. How is that possible?!
On client side I see only lots of "b" but anything sent inside the statement for (writer.println(message)). It's really strange, because when I print on the server SENDING MESSAGE TO CLIENT: [...] I see it in the console, but then the message is not sent.
What could it be the problem?
You need to read about how buffering works, and, in particular, learn to use the flush() method to instruct a buffered writer to actually send the data.
I'm reading a URL with the following code:
URL myURL = new URL("htpp://path_to_my_file");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (reader.ready()) {
String line = reader.readLine();
...
}
} catch (IOException e) {
throw new RuntimeException("Parsing of file failed: " + myURL, e);
}
Could it happen, that the file is not read completely? (because of network problems or something else?). If yes, is there a way to test it or even to avoid?
The background: I'm working on an application (not written by me up to this point) and users report me that parts of files are missing sometimes. It happens sporadically so my only guess was that something sometimes fails when the file is read in but I have too few java-background to be sure...
Yes, you'll know it's happened when you get an IOException as per the Reader.readLine docs.
So you'll want to catch the Exception, something like this:
try {
while (reader.ready()) {
String line = reader.readLine();
}
}
catch(IOException e) {
// Bah! Humbug!
// Should really log this too. So if you're using Log4j:
log.error("Error reading from URL " + myURL.toString(), e);
} finally {
try { if (reader != null) reader.close(); }catch(Exception e){}
}
Somewhere here, I found the following comment:
ready() != has more
ready() does not indicate that there is more data to be read. It only shows if a read will could block the thread. It is likely that it will return false before you read all data.
To find out if there is no more data check if readLine() returns null
It sounds that the implementation with reader.ready() causes my problem. Am I wrong with this assumption?