using GLib;
using Soup;
public class ControllerServer : Soup.Server {
public ControllerServer () {
Object (port: 8088);
assert (this != null);
this.add_handler (null, default_handler);
this.add_handler ("/index.html", index_handler);
this.add_handler ("/favicon.ico", favicon_handler);
this.add_websocket_handler ("/ws", null, null, websocket_handler);
}
private static void index_handler (Soup.Server server, Soup.Message msg, string path, GLib.HashTable? query, Soup.ClientContext client) {
string current_dir = Environment.get_current_dir();
uint8[] contents;
FileUtils.get_data ("%s/index.html".printf(current_dir), out contents);
msg.set_status (200);
msg.set_response ("text/html", Soup.MemoryUse.COPY, contents);
}
private static void favicon_handler (Soup.Server server, Soup.Message msg, string path, GLib.HashTable? query, Soup.ClientContext client) {
string current_dir = Environment.get_current_dir();
try {
uint8[] contents;
FileUtils.get_data ("%s/favicon.ico".printf(current_dir), out contents);
msg.set_response ("image/x-icon", Soup.MemoryUse.COPY, contents);
msg.set_status (200);
} catch (Error e) {
stderr.printf ("Error: %s\n", e.message);
}
}
private static void default_handler (Soup.Server server, Soup.Message msg, string path, GLib.HashTable? query, Soup.ClientContext client) {
if (path == "/") {
index_handler(server, msg, path, query, client);
return;
}
stderr.printf ("404 - request %s\n", path);
msg.set_response ("text/html", Soup.MemoryUse.COPY, "<html><body>Page not found</body></html>".data);
msg.set_status (404);
}
private static void websocket_handler(Soup.Server server, Soup.WebsocketConnection conn, string path, Soup.ClientContext client) {
stdout.printf ("Websocket handler goes here");
conn.message.connect ((type, message) => {
// receive messages en responds ...
stdout.printf ("Websocket message");
});
}
}
class Main.Application : GLib.Object {
public static int main(string[] args) {
stdout.printf ("Main application running\n");
MainLoop loop = new MainLoop();
const uint16 port = 8888;
InetAddress address = new InetAddress.loopback (SocketFamily.IPV4);
InetSocketAddress inetaddress = new InetSocketAddress (address, port);
GLib.Socket socket = new GLib.Socket (SocketFamily.IPV4, SocketType.STREAM, SocketProtocol.TCP);
socket.bind (inetaddress, true);
socket.listen ();
ControllerServer server = new ControllerServer();
server.listen_socket (socket, 0);
loop.run();
new MainLoop ().run ();
return 0;
}
}