Skip to content
Snippets Groups Projects
ScheduleServer.java 1.75 KiB
Newer Older
package com.example.schedulerapp;

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

public class ScheduleServer {
eyan_'s avatar
eyan_ committed
    private final RafisWeirdClass rafisWeirdClass;
    private final Set<UserThread> userThreads = new HashSet<>(); // notify when there are changes
    public ScheduleServer(String ip, int port, String dbURL, String dbUser, String dbPass) {
        this.port = port;
        this.rafisWeirdClass = new RafisWeirdClass(dbURL, dbUser, dbPass);
    }

    public void execute() {
        try (ServerSocket serverSocket = new ServerSocket(port, 50, InetAddress.getByName(ip))) {
            System.out.println("Server is listening on port " + port);

            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("New user connected");
eyan_'s avatar
eyan_ committed
                UserThread newUser = new UserThread(socket, this, this.rafisWeirdClass);
                userThreads.add(newUser);
                newUser.start();
            }
        } catch (IOException error) {
            System.out.println("Error in the server :" + error.getMessage());
            error.printStackTrace();
        }
    }

    void broadcast(String message) {
        for (UserThread aUser : userThreads) {
            aUser.sendMessage(message);
        }
    }

    void removeUser(UserThread aUser) {
        userThreads.remove(aUser);
    }

    public static void main(String[] args) {
        //Set "localhost" is working locally. Razer-Blade lan address (NOT static) is "172.16.1.99"
ArktikHunter's avatar
ArktikHunter committed
        ScheduleServer server = new ScheduleServer("localhost", 8989,
                "jdbc:mysql://localhost:3306/ScheduleApp", "root", "password");
        server.execute();
    }
}