import java.io.*; import java.net.*; import java.util.*; import java.nio.*; import java.nio.channels.*; import java.nio.charset.Charset; public class QuoteServerThread extends Thread { protected DatagramSocket socket = null; protected BufferedReader in = null; protected boolean moreQuotes = true; protected DatagramChannel dChannel; InetSocketAddress sockAddr; public QuoteServerThread() throws IOException { this("QuoteServerThread"); } public QuoteServerThread(String name) throws IOException { super(name); dChannel = DatagramChannel.open(); dChannel.socket().bind(new InetSocketAddress(4445)); try { in = new BufferedReader(new FileReader("one-liners.txt")); } catch (FileNotFoundException e) { System.err.println("Could not open quote file. Serving time instead."); } } public void run() { while (moreQuotes) { try { sockAddr = (InetSocketAddress)dChannel.receive(ByteBuffer.allocate(2000)); String dString = null; if (in == null) dString = new Date().toString(); else dString = getNextQuote(); System.out.println(dString.length() + ":" + dString); Charset charset = Charset.forName("ISO-8859-1"); ByteBuffer buf = charset.encode(dString); dChannel.send(buf, sockAddr); } catch (IOException e) { e.printStackTrace(); moreQuotes = false; } } try { dChannel.close(); } catch(IOException e) { e.printStackTrace(); } } protected String getNextQuote() { String returnValue = null; try { if ((returnValue = in.readLine()) == null) { in.close(); moreQuotes = false; returnValue = "No more quotes. Goodbye."; } } catch (IOException e) { returnValue = "IOException occurred in server."; } return returnValue; } }