Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

133
LINES

< > BotCompany Repo | #1000695 // Serve clock time under /time

JavaX source code - run with: x30.jar

!636

import java.util.*;
import java.io.*;
import java.net.*;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;

import javax.net.ssl.*;

main {
static class MyHTTPD extends NanoHTTPD {

     /**
     * Constructs an HTTP server on given port.
     */
    public MyHTTPD(int port) throws IOException {
        super(port);
    }


@Override
    public Response serve( String uri, Method method,
            Map<String, String> header, Map<String, String> parms,
            Map<String, String> files )
    {
        System.out.println( method + " '222" + uri + "' " );

      String ip = header.get("remote-addr");
      if (!ip.equals("127.0.0.1"))
        peers.add(ip);

      if (uri.equals("/time"))
        return newFixedLengthResponse(time24());

      String msg = "<html><body><h1>Hello server</h1>\n";
        if ( parms.get("username") == null )
            msg +=
                "<form action='?' method='get'>\n" +
                "  <p>Your name: <input type='text' name='username'></p>\n" +
                "</form>\n";
        else
            msg += "<p>Hello, " + parms.get("username") + "!</p>";

        msg += "uri: " + uri + "<br>";
        new List<String> links;
        for (String p : peers)
          links.add("<a href=\"http://" + p + ":8888\">" + p + "</a>");
        msg += "All known peers: " + join(", ", links);
        msg += "</body></html>\n";
        return newFixedLengthResponse(msg);
    }

static String join(String glue, Iterable<String> list) {
  new StringBuilder buf;
  boolean first = true;
  for (String s : list) {
    if (first) first = false;
    else buf.append(glue);
    buf.append(s);
  }
  return buf.toString();
}

    Response serveBinary(String path) {
      System.out.println("Serving " + path);
      long length = new File(path).length();
      System.out.println("File size: " + length);
      FileInputStream fis = null;
    try {
        fis = new FileInputStream(path);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return new Response(Status.OK, "application/binary", fis, length);
  }
}

  private static MyHTTPD server;
  private static int port = 8888;

  static new (Tree)Set<String> peers;
  
  psvm {
          server = new MyHTTPD(port);
          server.start();
          System.out.println("HTTP server started (listening on port " + port + "!)");
          printMyIPs();
          server.join(); // keep main thread alive
  }
  
  static void printMyIPs() {
  String ip;
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            // filters out 127.0.0.1 and inactive interfaces
            if (iface.isLoopback() || !iface.isUp())
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while(addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                if (addr instanceof Inet4Address) { // we still stick to the old stuff... until the new stuff comes along!
                  ip = addr.getHostAddress();
                  System.out.println("\nPlease visit http://" + ip + ":" +  port + " to see me!");
                }
            }
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
  }
  
  static String time24() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.US);
    //dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    return dateFormat.format(new Date());
  }
}

!include #1000433 // class NanoHTTP

Author comment

Began life as a copy of #1000596

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, teubizvjbppd, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1000695
Snippet name: Serve clock time under /time
Eternal ID of this version: #1000695/1
Text MD5: f44d9fb33025a64ee39ec83805d77acf
Author: stefan
Category: javax android
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-22 22:42:25
Source code size: 4111 bytes / 133 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 621 / 538
Referenced in: [show references]