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.