aboutsummaryrefslogtreecommitdiff
path: root/src/Server/SocketServer.java
blob: f3a8f2ea1ea119b1658edf37be36ee6b6133b294 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package Server;

import Store.Book;
import Store.User;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
import com.corundumstudio.socketio.Configuration;

public class SocketServer {
    public static SocketIOServer server;

    public SocketServer(Configuration config) {
        server = new SocketIOServer(config);

        server.addConnectListener(onConnected());
        server.addDisconnectListener(onDisconnected());

        server.addEventListener("login", JSONMessage.class, User.loginHandler());
        server.addEventListener("signUp", JSONMessage.class, User.signUpHandler());

        server.addEventListener("issue", JSONMessage.class, Book.issueHandler());
        server.addEventListener("return", JSONMessage.class, Book.returnHandler());
        server.addEventListener("getAllBooks", JSONMessage.class, Book.getListHandler(false));
        server.addEventListener("getAvailableBooks", JSONMessage.class, Book.getListHandler(true));
    }

    private ConnectListener onConnected() {
        return (client -> {
            System.out.println("New connection!");
        });
    }

    private DisconnectListener onDisconnected() {
        return (client -> {
            System.out.println("Disconnected!");
        });
    }

    public void start() {
        server.start();

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                server.stop();
            }
        }, "Shutdown-thread"));
    }

    public void stop() {
        server.stop();
    }
}