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

69
LINES

< > TinyBrain | #1009197 - serveHttpWithWebsockets

JavaX fragment (include)

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.net.ssl.*;

static class MyHTTPD extends NanoWebSocketServer {
  *(int port, O factory) {
    super(port, webSocketFactory(factory));
  }

  public Response serve(String uri, Method method,
    Map<String, String> header, Map<String, String> parms,
    Map<String, String> files) {
    S remoteAddr  = header.get("remote-addr");
    print("Serving URI: " + quote(uri) + " to: " + remoteAddr);
    
    /*if (nempty(remoteAddr) &&
      isTrue(callOpt(mc(), "isBlockedIP", remoteAddr))) {
      print("BLOCKED IP.");
      ret serve404();
    }*/
    
    try {
      Response response = cast callOpt(getMainClass(), "serve", uri, method, header, parms, files);
      if (response != null) ret response;
      S html = callHtmlMethod(getMainClass(), uri, parms);
      if (html != null)
        ret serveHTML(html);
      ret serve404();
    } catch (Throwable e) {
      printStackTrace(e);
      ret serveHTML("ERROR.");
    }
  }
}

static MyHTTPD serveHttpWithWebsockets_server;
static int serveHttpWithWebsockets_port = 8888;

static new TreeSet<String> serveHttpWithWebsockets_peers;

// factory: func(NanoHTTPD.IHTTPSession) -> WebSocket
static int serveHttpWithWebsockets(int port, O factory) ctex {
  serveHttpWithWebsockets_port = port;
  serveHttpWithWebsockets_server = new MyHTTPD(port, factory);
  serveHttpWithWebsockets_server.start();
  ret serveHttpWithWebsockets_port();
}

// serve on random port, return port number used
static int serveHttpWithWebsockets(O factory) {
  serveHttpWithWebsockets(0, factory);
  ret serveHttpWithWebsockets_port();
}

static int serveHttpWithWebsockets_port() {
  ret serveHttpWithWebsockets_server == null ? 0 : serveHttpWithWebsockets_server.getListeningPort();
}

static void cleanMeUp_serveHttpWithWebsockets() {
  if (serveHttpWithWebsockets_server != null) {
    serveHttpWithWebsockets_server.stop();
    serveHttpWithWebsockets_server = null;
  }
}

Author comment

Began life as a copy of #1001648

download  show line numbers  debug dex   

Travelled to 2 computer(s): cfunsshuasjs, tvejysmllsmz

No comments. add comment

Snippet ID: #1009197
Snippet name: serveHttpWithWebsockets
Eternal ID of this version: #1009197/8
Text MD5: 1ba17df02842d69b8a2c572bab4ea347
Author: stefan
Category: javax / networking
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-07-16 15:42:40
Source code size: 2184 bytes / 69 lines
Pitched / IR pitched: No / No
Views / Downloads: 44 / 65
Version history: 7 change(s)
Referenced in: [show]