Got a program here I've been writing, just a basic addition that the client responds to, but it seems that I don't have a concrete understand of DataInputStream & DataOutputStream methods like writeUTF() or flush(). I have the code that I'm trying to implement commented but whenever I run it, when the user reaches the second problem, the server crashes.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
//SERVER
public class BasicAdditionServer
{
int operand1;
int operand2;
int sum;
int correct;
int incorrect;
int questionNum = 0;
public static void main(String[] args) throws IOException {
ServerSocket se = new ServerSocket(9999);
Socket so = se.accept();
System.out.println("Client Connected.");
BasicAdditionServer bas = new BasicAdditionServer();
DataInputStream dis = new DataInputStream(so.getInputStream());
DataOutputStream dos = new DataOutputStream(so.getOutputStream());
String str = "";
String resp = "";
while (bas.questionNum < 10 || str.equals("stop"))
{
for(int z = 0; z < 10; z++)
{
resp = "";
//dos.writeUTF(bas.genCalc());
dos.writeUTF("[SERVER] - " + bas.genCalc());
dos.flush();
str = dis.readUTF();
if (bas.sum == Integer.parseInt(str))
{
bas.correct++;
// resp = "\nCORRECT!";
// dos.writeUTF(resp);
// //dos.flush();
}
else
{
bas.incorrect++;
// resp = "\nINCORRECT. CORRECT ANSWER --> " + bas.sum;
// dos.writeUTF(resp);
// //dos.flush();
}
}
//str = dis.readUTF();
//dos.writeUTF(str);
dos.writeUTF(bas.progressResult());
dos.flush();
/*
When you write data to a stream, it is not written immediately, and it is buffered.
So use flush() when you need to be sure that all your data from buffer is written.
We need to be sure that all the writes are completed before we close the stream,
and that is why flush() is called in file/buffered writer's close()
*/
}
dos.close();
dis.close();
so.close();
se.close();
System.out.println("[SERVER DISCONNECTED]");
}
public String genCalc()
{
sum = 0;
questionNum++;
String result = "";
Random rand = new Random();
operand1 = rand.nextInt(1,10);
operand2 = rand.nextInt(1,10);
sum = (operand1 + operand2);
result = ("[Question " + questionNum + "]: " + operand1 + " + " + operand2 + "?" );
return result;
}
public String progressResult()
{
return "[---RESULTS---] \n \n[CORRECT]: " + correct + " [INCORRECT]: " + incorrect + "\n\nPRESS ENTER TO EXIT... ";
}
}