My chat program's multi threaded server keeps on throwing exceptions when calling nextLine();
Code Java:
package chatprogram;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;
public class SunChatServerChild extends Thread {
static Scanner in;
static PrintWriter out;
//static HashSet<PrintWriter> writerSet = new HashSet<PrintWriter>();
//static HashSet<String> names = new HashSet<String>();
static Vector<PrintWriter> wV = new Vector<PrintWriter>();
static Vector<Scanner> sV = new Vector<Scanner>();
static Socket sock;
static int n;
public SunChatServerChild(Socket s, int cN) {
sock = s;
n = cN;
}
public void run() {
super.run();
try {
in = new Scanner(new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()), true);
wV.add(out);
while (true) {
String fromClient = in.nextLine(); // <--- problem right here when multiple clients are connected and chatting
broadCastMsg(fromClient);
}
} catch (IOException e) {
} finally {
in.close();
out.close();
}
}
private void broadCastMsg(String fromClient) {
Iterator<PrintWriter> it = wV.iterator();
while (it.hasNext()) {
PrintWriter writer = it.next();
writer.println(fromClient);
writer.flush();
}
}
}
cant figure out whats wrong, the program usually throws OutOfBoundsIndex, or NoSuchElementException: No line found.
Doesn't the the Server sit on the nextLine() until the client sends out a message. This only occurs when I have more than one client, and sometimes it works for a few messages back and forth then it throws the exceptions.
Re: My chat program's multi threaded server keeps on throwing exceptions when calling nextLine();
Why is your catch block empty? You shouldn't do that, and should at least print a stack trace there.
Re: My chat program's multi threaded server keeps on throwing exceptions when calling nextLine();
Nvm error has been resolved from using magical logic. Somehow my teachers identical code manages to run it flawlessly... : /
Re: My chat program's multi threaded server keeps on throwing exceptions when calling nextLine();
That's great, but still I urge you not to use empty catch blocks which is the coding equivalent of driving a car with blindfolds on.
Re: My chat program's multi threaded server keeps on throwing exceptions when calling nextLine();
Will take that into account! I finally understood what the bug was... I made the Scanner static so I believe every thread was sharing the same Scanner.