/* Copyright 2006 Laszlo Systems * Authors: David Nault and Benjamin Shine */ import java.io.*; import java.net.*; import javax.imageio.*; import java.util.Properties; import org.apache.commons.io.*; /* To compile: javac -cp commons-io-1.2.jar ImageServer.java To run: java -cp commons-io-1.2.jar:. ImageServer image.png Once running, get to it at http://localhost:9999/ Control initial delay with value of initialDelay in imageserver.properties */ public class ImageServer { static public void buildResponse( OutputStream os, byte[] imageBytes, int initialDelay) throws IOException, InterruptedException { // For testing purposes, we support an initial delay, // specified in milliseconds, before returning an image. if (initialDelay > 0) { System.out.println("Sleeping for " + initialDelay + "ms"); Thread.currentThread().sleep(initialDelay); System.out.println("Back from sleep."); } // Build HTTP headers os.write("HTTP/1.0 200 OK\r\n".getBytes()); // TODO The next line is where you would put a date; probably // a good idea to use "now". See GregorianCalendar, arg. // os.write("Date: Sun Aug 27 17:31:59 PDT 2006\r\n".getBytes()); // TODO: change the mime-type if you want to return something other // than a png. os.write("Content-Type: image/png\r\n".getBytes()); os.write(("Content-Length: " + imageBytes.length +"\r\n").getBytes()); os.write("\r\n".getBytes()); os.write(imageBytes); os.close(); } public static void main(String args[]) throws Exception { String imageFileName = "image.png"; if (args.length < 1) { System.out.println("Usage: java ImageServer "); } else { imageFileName = args[0]; } File imageFile = new File(imageFileName); System.out.println("Serving file : " + imageFile); byte[] imageBytes = FileUtils.readFileToByteArray(imageFile); System.out.println("image size in bytes: " + imageBytes.length); // declare a server socket and a client socket for the server // declare an input and an output stream ServerSocket echoServer = null; InputStream is = null; OutputStream os = null; Socket clientSocket = null; // Try to open a server socket on port 9999 try { echoServer = new ServerSocket(9999); } catch (IOException e) { System.out.println(e); } // Create a socket object from the ServerSocket to listen and accept // connections. while (true) { try { // Re-read the properties each time we serve up a response, so that // response properties can be changed without restarting the server. Properties props = new Properties(); props.load(new FileInputStream("imageserver.properties") ); String initialDelayStr = props.getProperty( "initialDelay", "0"); int initialDelay = Integer.parseInt(initialDelayStr); clientSocket = echoServer.accept(); System.out.println("starting response"); os = clientSocket.getOutputStream(); buildResponse(os, imageBytes, initialDelay); System.out.println("response complete"); System.out.println(); } catch (Exception e) { System.out.println(e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } } }