1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.newsclub.net.unix.demo.nanohttpd;
19
20 import java.io.File;
21 import java.io.IOException;
22 import java.net.InetAddress;
23 import java.net.ServerSocket;
24 import java.net.SocketAddress;
25
26 import org.newsclub.net.unix.AFSocketAddress;
27 import org.newsclub.net.unix.AFUNIXSocketAddress;
28 import org.newsclub.net.unix.demo.DemoHelper;
29 import org.newsclub.net.unix.demo.okhttp.OkHttpClientDemo;
30
31 import fi.iki.elonen.NanoHTTPD;
32
33
34
35
36
37
38
39
40
41 public final class NanoHttpdServerDemo extends NanoHTTPD {
42
43 public NanoHttpdServerDemo(SocketAddress socketAddress) throws IOException {
44 super(0);
45 setServerSocketFactory(new ServerSocketFactory() {
46
47 @Override
48 public ServerSocket create() throws IOException {
49 if (socketAddress instanceof AFSocketAddress) {
50 return ((AFSocketAddress) socketAddress).newForceBoundServerSocket();
51 } else {
52 ServerSocket serverSocket = new ServerSocket();
53 serverSocket.bind(socketAddress);
54 return serverSocket;
55 }
56 }
57 });
58 System.out.println("Address: " + socketAddress);
59 if (socketAddress instanceof AFUNIXSocketAddress) {
60 System.out.println("Try: curl --unix-socket " + ((AFUNIXSocketAddress) socketAddress)
61 .getPath() + " http://localhost/");
62 }
63 }
64
65 public static void main(String[] args) throws IOException {
66 SocketAddress addr = DemoHelper.parseAddress(args,
67 AFUNIXSocketAddress.of(new File("/tmp/junixsocket-http-server.sock")));
68
69 new NanoHttpdServerDemo(addr).start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
70 }
71
72 @Override
73 public Response serve(IHTTPSession session) {
74 return newFixedLengthResponse("Hello world from " + getSystemHostname() + "\n");
75 }
76
77 private static String getSystemHostname() {
78 try {
79 return InetAddress.getLocalHost().getHostName();
80 } catch (Exception e) {
81 e.printStackTrace();
82 return null;
83 }
84 }
85 }