List of usage examples for java.net ServerSocket accept
public Socket accept() throws IOException
From source file:HttpMirror.java
public static void main(String args[]) { try {/*ww w . j a v a 2 s . c o m*/ // Get the port to listen on int port = Integer.parseInt(args[0]); // Create a ServerSocket to listen on that port. ServerSocket ss = new ServerSocket(port); // Now enter an infinite loop, waiting for & handling connections. for (;;) { // Wait for a client to connect. The method will block; // when it returns the socket will be connected to the client Socket client = ss.accept(); // Get input and output streams to talk to the client BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); // Start sending our reply, using the HTTP 1.1 protocol out.print("HTTP/1.1 200 \r\n"); // Version & status code out.print("Content-Type: text/plain\r\n"); // The type of data out.print("Connection: close\r\n"); // Will close stream out.print("\r\n"); // End of headers // Now, read the HTTP request from the client, and send it // right back to the client as part of the body of our // response. The client doesn't disconnect, so we never get // an EOF. It does sends an empty line at the end of the // headers, though. So when we see the empty line, we stop // reading. This means we don't mirror the contents of POST // requests, for example. Note that the readLine() method // works with Unix, Windows, and Mac line terminators. String line; while ((line = in.readLine()) != null) { if (line.length() == 0) break; out.print(line + "\r\n"); } // Close socket, breaking the connection to the client, and // closing the input and output streams out.close(); // Flush and close the output stream in.close(); // Close the input stream client.close(); // Close the socket itself } // Now loop again, waiting for the next connection } // If anything goes wrong, print an error message catch (Exception e) { System.err.println(e); System.err.println("Usage: java HttpMirror <port>"); } }
From source file:org.sikuliserver.QueueReceiver.java
public static void main(String[] args) throws IOException { int port = 9001; if (args.length > 1 && args[0].equals("-p")) { port = Integer.valueOf(args[1]); }//from ww w.ja va 2s . c o m System.out.println("[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "] Launching a SikuliServer on port : " + port); ServerSocket serverSocket = new ServerSocket(port); System.out.println("[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "] Server Started and Listening..."); try { while (true) { Socket clientSocket = serverSocket.accept(); System.out.println("[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "] Connected to the clientSocket " + clientSocket.getLocalAddress().getHostName()); BufferedReader is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintStream os = new PrintStream(clientSocket.getOutputStream()); String line = ""; StringBuilder sb = new StringBuilder(); while (!(line = is.readLine()).equals("|ENDS|")) { sb.append(line); } System.out.println("[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "] Received :" + sb.toString()); JSONObject obj = new JSONObject(sb.toString()); String action = obj.getString("action"); String picture = obj.getString("picture"); String text = obj.getString("text"); String start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()); System.out.println("[" + start + "] Starting to perform :" + sb.toString()); if (action.equals("click") || action.equals("wait")) { URL url = new URL("file:///" + picture); InputStream istream = url.openStream(); //byte[] bytes = IOUtils.toByteArray(istream); //String imageDataString = Base64.encodeBase64URLSafeString(bytes); //byte[] data = Base64.decodeBase64(imageDataString); try (OutputStream stream = new FileOutputStream("sikuliPicture.png")) { //stream.write(data); stream.write(IOUtils.toByteArray(istream)); } } SikuliAction sikuliAction = new SikuliAction(); sikuliAction.doAction(action, picture, text); String end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()); System.out.println("[" + end + "] End of action :" + action + "(" + picture + ")"); os.println("[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "] Done"); os.println("|ENDR|"); } } catch (UnknownHostException e) { System.out.println("Unknown host: kq6py"); } catch (IOException e) { System.out.println("No I/O"); } catch (FindFailed ex) { Logger.getLogger(QueueReceiver.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { Logger.getLogger(QueueReceiver.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:nr.co.blky.skype.proxy.SkypeProxy.java
public static void main(String[] args) throws Exception { if (!(args.length == 1 || args.length == 5)) { usage();//from w w w . jav a 2 s. co m return; } Skype.setDebug(false); Skype.setDeamon(false); String idTmp = "GESHA";//here is default Application-ID for all version. Application application = Skype.addApplication(idTmp); System.out.println("connected as listener for app [" + application + "]"); //par#0 String COMMAND = args[0]; /* * skypeproxy listen */ if (LISTEN.equals(COMMAND)) { // Shell will be available only on the __host__ ChatMessageListener shellTmp = new ShellOverChat(); Skype.addChatMessageListener(shellTmp); // PrintStream outTmp = System.out; TunnelServer tunnelServer = new TunnelServer(outTmp); application.addApplicationListener(tunnelServer); } else if (SEND.equals(COMMAND)) { /* * skypeproxy send <contact> <localport> <remotehost> <remoteport> */ String CONTACT = args[1]; int LOCALPORT = Integer.parseInt(args[2]); String HOST = args[3]; String PORT = args[4]; ServerSocket ss = new ServerSocket(LOCALPORT); while (true) { log.info("listening port " + LOCALPORT + "..."); // accept the connection from my client final Socket sc = ss.accept(); log.info("accepted conenction ..."); Friend toFriend = null; //search friend for (Friend next : application.getAllConnectableFriends()) { log.info("check for " + next.getId()); if (next.getId().equalsIgnoreCase(CONTACT)) { ; toFriend = next; break; } } log.info("forwarding to [" + CONTACT + "].."); final Stream skypeStream = application.connect(toFriend)[0]; // send initial message String SiD = "" + ((int) (Math.random() * Integer.MAX_VALUE)); skypeStream.send("" + TunnelServer.HOST + "=" + HOST + TunnelServer.EOL + TunnelServer.PORT + "=" + PORT + TunnelServer.EOL + TunnelServer.ID + "=" + SiD + TunnelServer.EOL + TunnelServer.LISTENHOST + "=" + "LOCALHOST" + TunnelServer.EOL); File traceFileTmp = new File("trace.log"); final PrintStream traceOut = new PrintStream(traceFileTmp); OutputStream outS = sc.getOutputStream(); InputStream inS = sc.getInputStream(); final SkypeRelay tc = new SkypeRelay(skypeStream, outS, inS, traceOut); tc.SiD = SiD; skypeStream.addStreamListener(tc); String stringFromTo = "*:" + LOCALPORT + "->" + CONTACT + "@" + HOST + ":" + PORT + " SiD:" + SiD + "//getID=" + skypeStream.getId(); final Thread relayTmp = new Thread(tc, stringFromTo); relayTmp.start(); log.debug("NEW TUNNEL localhost:" + LOCALPORT + " ->" + toFriend.getId() + "@" + HOST + ":" + PORT + " inited."); } } }
From source file:ComplexCompany.java
public static void main(String args[]) throws Exception { ServerSocket servSocket; Socket fromClientSocket;// w w w . jav a 2s . com int cTosPortNumber = 1777; String str; ComplexCompany comp; servSocket = new ServerSocket(cTosPortNumber); System.out.println("Waiting for a connection on " + cTosPortNumber); fromClientSocket = servSocket.accept(); ObjectOutputStream oos = new ObjectOutputStream(fromClientSocket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(fromClientSocket.getInputStream()); while ((comp = (ComplexCompany) ois.readObject()) != null) { comp.printCompanyObject(); oos.writeObject("bye bye"); break; } oos.close(); fromClientSocket.close(); }
From source file:Bounce.java
/** * The main method.//from ww w . j a va2 s .c om */ public static void main(String[] args) { if (args.length < 3) { printUsage(); System.exit(1); } int localPort; try { localPort = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Bad local port value: " + args[0]); printUsage(); System.exit(2); return; } String hostname = args[1]; int remotePort; try { remotePort = Integer.parseInt(args[2]); } catch (NumberFormatException e) { System.err.println("Bad remote port value: " + args[2]); printUsage(); System.exit(3); return; } boolean shouldLog = args.length > 3 ? Boolean.valueOf(args[3]).booleanValue() : false; int numConnections = 0; try { ServerSocket ssock = new ServerSocket(localPort); while (true) { Socket incomingSock = ssock.accept(); Socket outgoingSock = new Socket(hostname, remotePort); numConnections++; InputStream incomingIn = incomingSock.getInputStream(); InputStream outgoingIn = outgoingSock.getInputStream(); OutputStream incomingOut = incomingSock.getOutputStream(); OutputStream outgoingOut = outgoingSock.getOutputStream(); if (shouldLog) { String incomingLogName = "in-log-" + incomingSock.getInetAddress().getHostName() + "(" + localPort + ")-" + numConnections + ".dat"; String outgoingLogName = "out-log-" + hostname + "(" + remotePort + ")-" + numConnections + ".dat"; OutputStream incomingLog = new FileOutputStream(incomingLogName); incomingOut = new MultiOutputStream(incomingOut, incomingLog); OutputStream outgoingLog = new FileOutputStream(outgoingLogName); outgoingOut = new MultiOutputStream(outgoingOut, outgoingLog); } PumpThread t1 = new PumpThread(incomingIn, outgoingOut); PumpThread t2 = new PumpThread(outgoingIn, incomingOut); t1.start(); t2.start(); } } catch (IOException e) { e.printStackTrace(); System.exit(3); } }
From source file:Server.java
public static void main(String args[]) { ServerSocket serverSocket = null; Utilities.printMsg("creating server socket"); try {/* w w w . j a v a 2s . co m*/ serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Unable to create server socket, " + e); System.exit(1); } Utilities.printMsg("accepting client connections"); while (true) { try { Socket clientSocket = serverSocket.accept(); new Client(clientSocket).start(); } catch (IOException e) { System.err.println("Unable to accept socket connection, " + e); System.exit(1); } } }
From source file:werewolf_server.Werewolf_Server.java
/** * @param args the command line arguments *//*from ww w . j a va 2 s . co m*/ public static void main(String[] args) throws IOException { // TODO code application logic here try { host = args[0]; port = Integer.parseInt(args[1]); n_player = Integer.parseInt(args[2]); int n_werewolf = 0; ServerSocket listener = new ServerSocket(port); Socket server; int i = 0; System.out.println("Server has been set up"); ConnectionHandler[] connection = new ConnectionHandler[n_player]; //waiting n_player while (i < n_player) { server = listener.accept(); //random role Random r = new Random(); int role = r.nextInt(2) + 1; if (role == 1 && n_werewolf <= n_player / 3) { n_werewolf++; } else { role = 0; } connection[i] = new ConnectionHandler(i, role, server); Thread t = new Thread(connection[i]); t.start(); i++; } System.out.println("Game Start"); System.out.println(n_werewolf); System.out.println("Day #1"); i = 0; while (i < n_player) { System.out.println("Player id:" + connection[i].player.getID()); if (connection[i].player.getRole() == 0) { System.out.println("Player role: Villager"); } else System.out.println("Player role: Werewolf"); System.out.println("Player role:" + connection[i].player.getStatus()); System.out.println("------------------------------------"); i++; } } catch (IOException ioe) { System.out.println("IOException on socket listen: " + ioe); ioe.printStackTrace(); } }
From source file:guardar.en.base.de.datos.MainServidor.java
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException { Mongo mongo = new Mongo("localhost", 27017); // nombre de la base de datos DB database = mongo.getDB("paginas"); // coleccion de la db DBCollection collection = database.getCollection("indice"); DBCollection collection_textos = database.getCollection("tabla"); ArrayList<String> lista_textos = new ArrayList(); try {//from w w w . j av a 2 s . co m ServerSocket servidor = new ServerSocket(4545); // Crear un servidor en pausa hasta que un cliente llegue. while (true) { String aux = new String(); lista_textos.clear(); Socket clienteNuevo = servidor.accept();// Si llega se acepta. // Queda en pausa otra vez hasta que un objeto llegue. ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream()); JSONObject request = (JSONObject) entrada.readObject(); String b = (String) request.get("id"); //hacer una query a la base de datos con la palabra que se quiere obtener BasicDBObject query = new BasicDBObject("palabra", b); DBCursor cursor = collection.find(query); ArrayList<DocumentosDB> lista_doc = new ArrayList<>(); // de la query tomo el campo documentos y los agrego a una lista try { while (cursor.hasNext()) { //System.out.println(cursor.next()); BasicDBList campo_documentos = (BasicDBList) cursor.next().get("documentos"); // en el for voy tomando uno por uno los elementos en el campo documentos for (Iterator<Object> it = campo_documentos.iterator(); it.hasNext();) { BasicDBObject dbo = (BasicDBObject) it.next(); //DOC tiene id y frecuencia DocumentosDB doc = new DocumentosDB(); doc.makefn2(dbo); //int id = (int)doc.getId_documento(); //int f = (int)doc.getFrecuencia(); lista_doc.add(doc); //******************************************* //******************************************** //QUERY A LA COLECCION DE TEXTOS /* BasicDBObject query_textos = new BasicDBObject("id", doc.getId_documento());//query DBCursor cursor_textos = collection_textos.find(query_textos); try { while (cursor_textos.hasNext()) { DBObject obj = cursor_textos.next(); String titulo = (String) obj.get("titulo"); titulo = titulo + "\n\n"; String texto = (String) obj.get("texto"); String texto_final = titulo + texto; aux = texto_final; lista_textos.add(texto_final); } } finally { cursor_textos.close(); }*/ //System.out.println(doc.getId_documento()); //System.out.println(doc.getFrecuencia()); } // end for } //end while query } finally { cursor.close(); } // ordeno la lista de menor a mayor Collections.sort(lista_doc, new Comparator<DocumentosDB>() { @Override public int compare(DocumentosDB o1, DocumentosDB o2) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. return o1.getFrecuencia().compareTo(o2.getFrecuencia()); } }); int tam = lista_doc.size() - 1; for (int j = tam; j >= 0; j--) { BasicDBObject query_textos = new BasicDBObject("id", (int) lista_doc.get(j).getId_documento().intValue());//query DBCursor cursor_textos = collection_textos.find(query_textos);// lo busco try { while (cursor_textos.hasNext()) { DBObject obj = cursor_textos.next(); String titulo = "*******************************"; titulo += (String) obj.get("titulo"); int f = (int) lista_doc.get(j).getFrecuencia().intValue(); String strinf = Integer.toString(f); titulo += "******************************* frecuencia:" + strinf; titulo = titulo + "\n\n"; String texto = (String) obj.get("texto"); String texto_final = titulo + texto + "\n\n"; aux = aux + texto_final; //lista_textos.add(texto_final); } } finally { cursor_textos.close(); } } //actualizar el cache try { Socket cliente_cache = new Socket("localhost", 4500); // nos conectamos con el servidor ObjectOutputStream mensaje_cache = new ObjectOutputStream(cliente_cache.getOutputStream()); // get al output del servidor, que es cliente : socket del cliente q se conecto al server JSONObject actualizacion_cache = new JSONObject(); actualizacion_cache.put("actualizacion", 1); actualizacion_cache.put("busqueda", b); actualizacion_cache.put("respuesta", aux); mensaje_cache.writeObject(actualizacion_cache); // envio el msj al servidor } catch (Exception ex) { } //RESPONDER DESDE EL SERVIDORIndex al FRONT ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj resp.writeObject(aux); System.out.println("msj enviado desde el servidor"); } } catch (IOException ex) { Logger.getLogger(MainServidor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.annuletconsulting.homecommand.server.HomeCommand.java
/** * This class will accept commands from a node in each room. For it to react to events on the server * computer, it must be also running as a node. However the server can cause all nodes to react * to an event happening on any node, such as an email or text arriving. A call on a node device * could pause all music devices, for example. * /*from www . java 2 s . co m*/ * @param args */ public static void main(String[] args) { try { socket = Integer.parseInt(HomeComandProperties.getInstance().getServerPort()); nonJavaUserModulesPath = HomeComandProperties.getInstance().getNonJavaUserDir(); } catch (Exception exception) { System.out.println("Error loading from properties file."); exception.printStackTrace(); } try { sharedKey = HomeComandProperties.getInstance().getSharedKey(); if (sharedKey == null) System.out.println("shared_key is null, commands without valid signatures will be processed."); } catch (Exception exception) { System.out.println("shared_key not found in properties file."); exception.printStackTrace(); } try { if (args.length > 0) { String arg0 = args[0]; if (arg0.equals("help") || arg0.equals("?") || arg0.equals("usage") || arg0.equals("-help") || arg0.equals("-?")) { System.out.println( "The defaults can be changed by editing the HomeCommand.properties file, or you can override them temporarily using command line options."); System.out.println("\nHome Command Server command line overrride usage:"); System.out.println( "hcserver [server_port] [java_user_module_directory] [non_java_user_module_directory]"); //TODO make hcserver.sh System.out.println("\nDefaults:"); System.out.println("server_port: " + socket); System.out.println("java_user_module_directory: " + userModulesPath); System.out.println("non_java_user_module_directory: " + nonJavaUserModulesPath); System.out.println("\n2013 | Annulet, LLC"); } socket = Integer.parseInt(arg0); } if (args.length > 1) userModulesPath = args[1]; if (args.length > 2) nonJavaUserModulesPath = args[2]; System.out.println("Config loaded, initializing modules."); modules.add(new HueLightModule()); System.out.println("HueLightModule initialized."); modules.add(new QuestionModule()); System.out.println("QuestionModule initialized."); modules.add(new MathModule()); System.out.println("MathModule initialized."); modules.add(new MusicModule()); System.out.println("MusicModule initialized."); modules.add(new NonCopyrightInfringingGenericSpaceExplorationTVShowModule()); System.out.println("NonCopyrightInfringingGenericSpaceExplorationTVShowModule initialized."); modules.add(new HelpModule()); System.out.println("HelpModule initialized."); modules.add(new SetUpModule()); System.out.println("SetUpModule initialized."); modules.addAll(NonJavaUserModuleLoader.loadModulesAt(nonJavaUserModulesPath)); System.out.println("NonJavaUserModuleLoader initialized."); ServerSocket serverSocket = new ServerSocket(socket); System.out.println("Listening..."); while (!end) { Socket socket = serverSocket.accept(); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); PrintWriter output = new PrintWriter(socket.getOutputStream(), true); int character; StringBuffer inputStrBuffer = new StringBuffer(); while ((character = isr.read()) != 13) { inputStrBuffer.append((char) character); } System.out.println(inputStrBuffer.toString()); String[] cmd; // = inputStrBuffer.toString().split(" "); String result = "YOUR REQUEST WAS NOT VALID JSON"; if (inputStrBuffer.substring(0, 1).equals("{")) { nodeType = extractElement(inputStrBuffer.toString(), "node_type"); if (sharedKey != null) { if (validateSignature(extractElement(inputStrBuffer.toString(), "time_stamp"), extractElement(inputStrBuffer.toString(), "signature"))) { if ("Y".equalsIgnoreCase(extractElement(inputStrBuffer.toString(), "cmd_encoded"))) cmd = decryptCommand(extractElement(inputStrBuffer.toString(), "command")); else cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } else result = "YOUR SIGNATURE DID NOT MATCH, CHECK SHARED KEY"; } else { cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } } System.out.println(result); output.print(result); output.print((char) 13); output.close(); isr.close(); socket.close(); } serverSocket.close(); System.out.println("Shutting down."); } catch (Exception exception) { exception.printStackTrace(); } }
From source file:org.jets3t.service.FakeS3Server.java
/** * @param args/*from ww w .j a v a 2 s . c o m*/ */ public static void main(String[] args) throws Exception { AWSCredentials fakeAwsCredentials = new AWSCredentials("fake-aws-access-key", "fake-aws-secret-key"); int port = 443; ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault(); ServerSocket ssocket = ssocketFactory.createServerSocket(port); System.out.println("Accepting connections on port 443"); while (port == 443) { // Listen for connections Socket socket = ssocket.accept(); System.out.println("Opened connection"); // Create streams to securely send and receive data to the client InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { String receivedDataStr = new String(buffer, 0, read); String requestActionAndHeaders = receivedDataStr.substring(0, receivedDataStr.indexOf("\r\n\r\n") + 4); System.out.println(requestActionAndHeaders); if (requestActionAndHeaders.startsWith("GET")) { String path = requestActionAndHeaders.substring(4, requestActionAndHeaders.indexOf(' ', 4)); if (path.startsWith("/jets3t-")) { // Return fake AWS credentials. String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakeAWSCredentials\r\n" + "x-amz-request-id: FakeAWSCredentials\r\n" + "Date: Thu, 24 May 2007 13:39:21 GMT\r\n" + "Cache-Control: max-age=259200\r\n" + "Last-Modified: Wed, 27 Dec 2006 02:37:58 GMT\r\n" + "ETag: \"fa5d6b0ea9716cf692b286b6aa187f3d\"\r\n" + "Content-Type: application/octet-stream\r\n" + "Content-Length: 139\r\n" + "Server: AmazonS3\r\n\r\n"; out.write(headers.getBytes("UTF-8")); fakeAwsCredentials.save("please", out); } else if (path.equals("/")) { // Return fake bucket listing. String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakeBucketListing\r\n" + "x-amz-request-id: FakeBucketListing\r\n" + "Date: Thu, 24 May 2007 13:39:23 GMT\r\n" + "Content-Type: application/xml\r\n" + "Transfer-Encoding: chunked\r\n" + "Server: AmazonS3\r\n\r\n"; String bucketListing = "17b\r\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" + "<Owner><ID>1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c</ID>" + "<DisplayName>jamesmurty</DisplayName></Owner>" + "<Buckets><Bucket><Name>TestUploadBucket</Name>" + "<CreationDate>2006-12-13T21:21:14.000Z</CreationDate>" + "</Bucket></Buckets></ListAllMyBucketsResult>" + "\r\n0\r\n\r\n"; out.write(headers.getBytes("UTF-8")); out.write(bucketListing.getBytes("UTF-8")); } else if (path.startsWith("/TestUploadBucket")) { // Return empty bucket contents String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakeBucketContents\r\n" + "x-amz-request-id: FakeBucketContents\r\n" + "Date: Thu, 24 May 2007 13:39:23 GMT\r\n" + "Content-Type: application/xml\r\n" + "Transfer-Encoding: chunked\r\n" + "Server: AmazonS3\r\n\r\n"; String bucketContents = "f2\r\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" + "<Name>TestUploadBucket</Name><Prefix></Prefix><Marker></Marker>" + "<MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated>" + "</ListBucketResult>" + "\r\n0\r\n\r\n"; out.write(headers.getBytes("UTF-8")); out.write(bucketContents.getBytes("UTF-8")); } else { System.out.println("ERROR: Unrecognised GET request"); } } else if (requestActionAndHeaders.startsWith("PUT")) { long contentLength = 0; String clientProvidedHash = "NONE"; // Determine content length. int searchIndex = requestActionAndHeaders.indexOf("Content-Length: ") + "Content-Length: ".length(); contentLength = (new Long(requestActionAndHeaders.substring(searchIndex, requestActionAndHeaders.indexOf('\r', searchIndex)))).longValue(); // Determine content MD5 (hex encoded). searchIndex = requestActionAndHeaders.indexOf("Content-MD5: ") + "Content-MD5: ".length(); if (searchIndex >= -1) { clientProvidedHash = requestActionAndHeaders.substring(searchIndex, requestActionAndHeaders.indexOf('\r', searchIndex)); } // Read all PUT data provided by client, generating an MD5 hash as we go. System.out.println("Receiving " + contentLength + " bytes from client"); MessageDigest digest = MessageDigest.getInstance("MD5"); long putdataAlreadyRead = read - requestActionAndHeaders.length(); // read - (requestActionAndHeaders.lastIndexOf("\r\n") + 2); digest.update(buffer, (int) (read - putdataAlreadyRead), (int) putdataAlreadyRead); byte[] putdata = new byte[8192]; int putdataRead = 0; while ((putdataRead = in.read(putdata)) != -1) { digest.update(putdata, 0, putdataRead); putdataAlreadyRead += putdataRead; if (putdataAlreadyRead == contentLength) { System.out.println("PUT object upload is complete"); break; } } if (putdataAlreadyRead != contentLength) { System.err.println( "ERROR: Expected " + contentLength + " bytes but received " + putdataAlreadyRead); continue; } String receivedDataHashAsHex = new String(Base64.encodeBase64(digest.digest()), "UTF-8"); // Generate the headers appropriate for the PUT object. String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakePUT\r\n" + "x-amz-request-id: FakePUT\r\n" + "Date: Thu, 24 May 2007 15:12:30 GMT\r\n" + "ETag: \"" + receivedDataHashAsHex + "\"\r\n" + "Content-Length: 0\r\n" + "Server: AmazonS3\r\n\r\n"; out.write(headers.getBytes("UTF-8")); out.flush(); // Compare expected hash (supplied by client) verses actual hash (for retrieved data) if (!receivedDataHashAsHex.equals(clientProvidedHash)) { System.err.println("ERROR: Client-side hash " + clientProvidedHash + " does not match hash of received data " + receivedDataHashAsHex); } else { System.out.println("SUCCESS: Client-side hash matches hash of received data: " + receivedDataHashAsHex); } } else { System.out.println("ERROR: Unrecognised input"); } } // Close the socket System.out.println("Closing connection"); in.close(); out.close(); } }