/** * @ioHandler.java * * Klass som hanterar trafiken, * skickar och ytar emot meddelanden. * * @author Karl-Adam Karlsson * @version 1.0 06/10/01 * * */ import java.util.LinkedList; import java.io.*; import java.net.*; public class ioHandler implements Runnable{ private int port; InetAddress address; private LinkedList messages; private Socket sock; private InputStream inputS; private BufferedReader reader; private PrintStream output; private Boolean on; private Client myChat; public ioHandler(String aIPno, int aPort, Client aChat){ port = aPort; messages = new LinkedList(); on = true; myChat = aChat; System.out.println(aPort); //set up address try{ address = InetAddress.getByName(aIPno); }catch(UnknownHostException e){System.out.println(e);} // Set up socket try { sock = new Socket(address, aPort); } catch(IOException e) { e.printStackTrace(); System.out.println("Exception, creating socket failed."); return; } //Set up input Stream try { inputS = sock.getInputStream(); } catch(IOException e) { System.out.println("Exception, InputStream creation failed."); return; } // Set up buffered Reader reader = new BufferedReader(new InputStreamReader(inputS)); //set up outputStream //try { // output = new DataOutputStream(sock.getOutputStream()); //}catch (IOException e) { // System.out.println(e); //} //Set up printstream try { output = new PrintStream(sock.getOutputStream()); } catch (IOException e) { System.out.println("Exception, creating PrintStream"); System.out.println(e); } } /* * Anropas när man vill skicka meddelande, lägger till meddelandet i meddelandekön. * */ public void sendMess(String aMess){ //System.out.println(on); messages.addLast(aMess); } /* * Disablar while loopen i run. * */ public void disable(){ on = false; } /* * Stänger allt. */ public void closeAll(){ output.close(); try { inputS.close(); }catch(IOException e) {} try { reader.close(); }catch(IOException e) {} try { sock.close(); }catch(IOException e) {} } /* * Run, tar emot och skickar meddelanden, och sover 350ms. * */ public void run(){ while(on){ if(messages.size()>0){ System.out.println("ska skicka"); System.out.println(messages.getFirst().toString()); output.print(messages.getFirst()); messages.removeFirst(); } String line=""; try { if(reader.ready()){ line = reader.readLine(); myChat.printMessage(line); } } catch(IOException e) { e.printStackTrace(); // System.exit(6); } try {Thread.sleep(350);} catch(InterruptedException e){System.out.println("Thread InterruptedException");} }//end of while //Om vi är här har vi disablat chatten. closeAll(); } } /* * * * InetAddress address = null; try { address = InetAddress.getByName(args[0]); } catch(UnknownHostException e) { e.printStackTrace(); // System.exit(2); return; } * * */