Newer
Older
package com.example.scheduler_server;
import java.io.*;
import java.net.*;
import java.util.*;
/*
Name: ScheduleServer
Description: Establishes the connection to the database, and opens the scheduling sever for scheduling clients
to connect to.
*/
Rafi Zereselasie (raz070)
committed
private final DataBaseQuery dbQuery;
private final int port;
private final String ip;
private final Set<UserThread> userThreads = new HashSet<>(); // notify when there are changes
/*
Name: ScheduleServer
Parameters:
String ip: The IP address for the server to bind to.
int port: The port the server will listen to.
String dbURL: The URL of the database
String dbUser: The username of the database.
String dbPass: The password of the database.
Description: Changes when the shift starts.
Return: ScheduleServer
*/
public ScheduleServer(String ip, int port, String dbURL, String dbUser, String dbPass) {
this.ip = ip;
Rafi Zereselasie (raz070)
committed
this.dbQuery = new DataBaseQuery(dbURL, dbUser, dbPass);
/*
Name: execute
Description: This runs on an infinite loop where it waits for new clients makes a new thread for its requests.
*/
try (ServerSocket serverSocket = new ServerSocket(port, 50, InetAddress.getByName(ip))) {
System.out.println("Scheduling server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New user connected");
Rafi Zereselasie (raz070)
committed
UserThread newUser = new UserThread(socket, this, this.dbQuery);
userThreads.add(newUser);
newUser.start();
}
} catch (IOException error) {
System.out.println("Error in the server :" + error.getMessage());
error.printStackTrace();
}
}
/*
Name: Broadcast
Parameters:
String message: Message to be sent to all the clients.
Description: Sends a message to all current online schedule clients.
Return: void
*/
void broadcast(String message) {
for (UserThread aUser : userThreads) {
aUser.sendMessage(message);
}
}
/*
Name: removeUser
Parameters:
UserThread aUser: The thread responsible for listening and sending message to a scheduling client.
Description: Removes the connection of a scheduling client from the server.
Return: void
*/
void removeUser(UserThread aUser) {
userThreads.remove(aUser);
}
public static void main(String[] args) throws IOException {
Properties serverProp = new Properties();
FileInputStream in = new FileInputStream("./src/main/java/com/example/scheduler_server/server.properties");
serverProp.load(in);
ScheduleServer server = new ScheduleServer(serverProp.getProperty("ipAddress"), Integer.parseInt(serverProp.getProperty("port")),
serverProp.getProperty("dbURL"), serverProp.getProperty("dbUser"), serverProp.getProperty("dbPass"));