/* Class Receiver By Martin Carlsson Internetprogrammering 4 Course */ import java.net.*; import org.jdom.*; import org.jdom.input.*; import java.io.*; /** *Class for receiving messages from a Chat Server. *@author Martin Carlsson */ public class Receiver implements Runnable { private BufferedReader in; private String host; private Chat gui; private SAXBuilder builder; private boolean looping = true; /** *Constructs a Receiver object *@param socket the socket used for receiving messages *@param gui Reference to the GUI */ public Receiver(Chat gui, Socket socket) { builder = new SAXBuilder(true); this.gui = gui; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); gui.setTitle("Java Chat Client on: " + socket.getInetAddress().getHostName()+ " :port " + socket.getPort()); } catch(IOException iOe) { String problem = "Problem connecting to host! Check your connection! \n" + iOe.getMessage(); System.err.println(problem +"\n" + iOe.getMessage()); iOe.printStackTrace(); gui.setErrorMessage(problem); } } /** *Creates an XML document object of incoming messages from the chat server */ public void run() { try { String inStream = null; while ((inStream = in.readLine()) != null) { try { synchronized(this) { while (!looping) wait(); } } catch (InterruptedException e) { } try { Document doc = builder.build(new StringReader(inStream)); gui.setMessage(doc); } catch(JDOMException jDe) { String problem = "COULDN'T PARSE A MESSAGE: " + inStream + "\n" + jDe; System.err.println(problem); gui.setErrorMessage(problem); } catch(Exception e) { System.err.println("Unknown error:" + e.getMessage()); } } } catch(IOException iOe) { } } /** *Stops the thread loop; the thread is put in a waiting mode */ public synchronized void setLooping(boolean b) { looping = b; if (looping) notify(); } /** *Closes the input stream */ public void closeInStream() { try { if(in !=null) in.close(); } catch(IOException iE) { } } } // End class Receiver