added Handout
This commit is contained in:
parent
94c220fbb9
commit
0886f896b2
|
@ -0,0 +1,64 @@
|
||||||
|
/*
|
||||||
|
* Gradle build configuration for specific lab module / exercise
|
||||||
|
*/
|
||||||
|
// enabled plugins
|
||||||
|
plugins {
|
||||||
|
// Support for Java
|
||||||
|
id 'java'
|
||||||
|
// Support for Java applications
|
||||||
|
id 'application'
|
||||||
|
// Support for JavaFX
|
||||||
|
id 'org.openjfx.javafxplugin' version '0.0.11'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Project/Module information
|
||||||
|
description = 'Uebung Multichat – Client Application'
|
||||||
|
group = 'ch.zhaw.pm2'
|
||||||
|
version = '2022.1'
|
||||||
|
|
||||||
|
// Dependency configuration
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// dependency to the protocol library
|
||||||
|
implementation project(':protocol')
|
||||||
|
// JUnit Jupiter dependencies
|
||||||
|
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.+'
|
||||||
|
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.+'
|
||||||
|
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.+'
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configuration for Application plugin
|
||||||
|
application {
|
||||||
|
// Define the main class for the application.
|
||||||
|
mainClass = 'ch.zhaw.pm2.multichat.client.Client'
|
||||||
|
}
|
||||||
|
|
||||||
|
javafx {
|
||||||
|
version = '17.0.2'
|
||||||
|
modules = [ 'javafx.controls', 'javafx.fxml' ]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test task configuration
|
||||||
|
test {
|
||||||
|
// Use JUnit platform for unit tests
|
||||||
|
useJUnitPlatform()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Java plugin configuration
|
||||||
|
java {
|
||||||
|
// By default the Java version of the gradle process is used as source/target version.
|
||||||
|
// This can be overridden, to ensure a specific version. Enable only if required.
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17 // ensure Java source code compatibility
|
||||||
|
// targetCompatibility = JavaVersion.VERSION_17 // version of the created byte-code
|
||||||
|
|
||||||
|
// Java compiler specific options
|
||||||
|
compileJava {
|
||||||
|
// source files should be UTF-8 encoded
|
||||||
|
options.encoding = 'UTF-8'
|
||||||
|
// for more options see https://docs.gradle.org/current/dsl/org.gradle.api.tasks.compile.CompileOptions.html
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,218 @@
|
||||||
|
package ch.zhaw.pm2.multichat.client;
|
||||||
|
|
||||||
|
import ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State;
|
||||||
|
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
||||||
|
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.event.EventHandler;
|
||||||
|
import javafx.fxml.FXML;
|
||||||
|
import javafx.scene.control.Button;
|
||||||
|
import javafx.scene.control.TextArea;
|
||||||
|
import javafx.scene.control.TextField;
|
||||||
|
import javafx.scene.layout.Pane;
|
||||||
|
import javafx.stage.WindowEvent;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
||||||
|
|
||||||
|
public class ChatWindowController {
|
||||||
|
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
|
||||||
|
private ClientConnectionHandler connectionHandler;
|
||||||
|
private ClientMessageList messages;
|
||||||
|
|
||||||
|
private final WindowCloseHandler windowCloseHandler = new WindowCloseHandler();
|
||||||
|
|
||||||
|
@FXML private Pane rootPane;
|
||||||
|
@FXML private TextField serverAddressField;
|
||||||
|
@FXML private TextField serverPortField;
|
||||||
|
@FXML private TextField userNameField;
|
||||||
|
@FXML private TextField messageField;
|
||||||
|
@FXML private TextArea messageArea;
|
||||||
|
@FXML private Button connectButton;
|
||||||
|
@FXML private Button sendButton;
|
||||||
|
@FXML private TextField filterValue;
|
||||||
|
|
||||||
|
|
||||||
|
@FXML
|
||||||
|
public void initialize() {
|
||||||
|
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
|
||||||
|
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT));
|
||||||
|
stateChanged(NEW);
|
||||||
|
messages = new ClientMessageList(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void applicationClose() {
|
||||||
|
connectionHandler.setState(DISCONNECTED);
|
||||||
|
}
|
||||||
|
|
||||||
|
@FXML
|
||||||
|
private void toggleConnection () {
|
||||||
|
if (connectionHandler == null || connectionHandler.getState() != CONNECTED) {
|
||||||
|
connect();
|
||||||
|
} else {
|
||||||
|
disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void connect() {
|
||||||
|
try {
|
||||||
|
messages = new ClientMessageList(this); // clear message list
|
||||||
|
startConnectionHandler();
|
||||||
|
connectionHandler.connect();
|
||||||
|
} catch(ChatProtocolException | IOException e) {
|
||||||
|
writeError(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void disconnect() {
|
||||||
|
if (connectionHandler == null) {
|
||||||
|
writeError("No connection handler");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
connectionHandler.disconnect();
|
||||||
|
} catch (ChatProtocolException e) {
|
||||||
|
writeError(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@FXML
|
||||||
|
private void message() {
|
||||||
|
if (connectionHandler == null) {
|
||||||
|
writeError("No connection handler");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String messageString = messageField.getText().strip();
|
||||||
|
Matcher matcher = messagePattern.matcher(messageString);
|
||||||
|
if (matcher.find()) {
|
||||||
|
String receiver = matcher.group(1);
|
||||||
|
String message = matcher.group(2);
|
||||||
|
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
|
||||||
|
try {
|
||||||
|
connectionHandler.message(receiver, message);
|
||||||
|
} catch (ChatProtocolException e) {
|
||||||
|
writeError(e.getMessage());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
writeError("Not a valid message format.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@FXML
|
||||||
|
private void applyFilter( ) {
|
||||||
|
this.redrawMessageList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void startConnectionHandler() throws IOException {
|
||||||
|
String userName = userNameField.getText();
|
||||||
|
String serverAddress = serverAddressField.getText();
|
||||||
|
int serverPort = Integer.parseInt(serverPortField.getText());
|
||||||
|
connectionHandler = new ClientConnectionHandler(
|
||||||
|
NetworkHandler.openConnection(serverAddress, serverPort), userName,
|
||||||
|
this);
|
||||||
|
new Thread(connectionHandler).start();
|
||||||
|
|
||||||
|
// register window close handler
|
||||||
|
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void terminateConnectionHandler() {
|
||||||
|
// unregister window close handler
|
||||||
|
rootPane.getScene().getWindow().removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
||||||
|
if (connectionHandler != null) {
|
||||||
|
connectionHandler.stopReceiving();
|
||||||
|
connectionHandler = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stateChanged(State newState) {
|
||||||
|
// update UI (need to be run in UI thread: see Platform.runLater())
|
||||||
|
Platform.runLater(new Runnable() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
connectButton.setText((newState == CONNECTED || newState == CONFIRM_DISCONNECT) ? "Disconnect" : "Connect");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (newState == DISCONNECTED) {
|
||||||
|
terminateConnectionHandler();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUserName(String userName) {
|
||||||
|
Platform.runLater(new Runnable() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
userNameField.setText(userName);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setServerAddress(String serverAddress) {
|
||||||
|
Platform.runLater(new Runnable() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
serverAddressField.setText(serverAddress);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setServerPort(int serverPort) {
|
||||||
|
Platform.runLater(new Runnable() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
serverPortField.setText(Integer.toString(serverPort));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addMessage(String sender, String receiver, String message) {
|
||||||
|
messages.addMessage(ClientMessageList.MessageType.MESSAGE, sender, receiver, message);
|
||||||
|
this.redrawMessageList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addInfo(String message) {
|
||||||
|
messages.addMessage(ClientMessageList.MessageType.INFO, null, null, message);
|
||||||
|
this.redrawMessageList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addError(String message) {
|
||||||
|
messages.addMessage(ClientMessageList.MessageType.ERROR, null, null, message);
|
||||||
|
this.redrawMessageList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clearMessageArea() {
|
||||||
|
this.messageArea.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private void redrawMessageList() {
|
||||||
|
Platform.runLater(() -> messages.writeFilteredMessages(filterValue.getText().strip()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void writeError(String message) {
|
||||||
|
this.messageArea.appendText(String.format("[ERROR] %s\n", message));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void writeInfo(String message) {
|
||||||
|
this.messageArea.appendText(String.format("[INFO] %s\n", message));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void writeMessage(String sender, String reciever, String message) {
|
||||||
|
this.messageArea.appendText(String.format("[%s -> %s] %s\n", sender, reciever, message));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class WindowCloseHandler implements EventHandler<WindowEvent> {
|
||||||
|
public void handle(WindowEvent event) {
|
||||||
|
applicationClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package ch.zhaw.pm2.multichat.client;
|
||||||
|
|
||||||
|
import javafx.application.Application;
|
||||||
|
|
||||||
|
public class Client {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// Start UI
|
||||||
|
System.out.println("Starting Client Application");
|
||||||
|
Application.launch(ClientUI.class, args);
|
||||||
|
System.out.println("Client Application ended");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,202 @@
|
||||||
|
package ch.zhaw.pm2.multichat.client;
|
||||||
|
|
||||||
|
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
||||||
|
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||||
|
|
||||||
|
import java.io.EOFException;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.SocketException;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
||||||
|
|
||||||
|
public class ClientConnectionHandler implements Runnable {
|
||||||
|
private final NetworkHandler.NetworkConnection<String> connection;
|
||||||
|
private final ChatWindowController controller;
|
||||||
|
|
||||||
|
// Data types used for the Chat Protocol
|
||||||
|
private static final String DATA_TYPE_CONNECT = "CONNECT";
|
||||||
|
private static final String DATA_TYPE_CONFIRM = "CONFIRM";
|
||||||
|
private static final String DATA_TYPE_DISCONNECT = "DISCONNECT";
|
||||||
|
private static final String DATA_TYPE_MESSAGE = "MESSAGE";
|
||||||
|
private static final String DATA_TYPE_ERROR = "ERROR";
|
||||||
|
|
||||||
|
public static final String USER_NONE = "";
|
||||||
|
public static final String USER_ALL = "*";
|
||||||
|
|
||||||
|
private String userName = USER_NONE;
|
||||||
|
private State state = NEW;
|
||||||
|
|
||||||
|
enum State {
|
||||||
|
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
||||||
|
String userName,
|
||||||
|
ChatWindowController controller) {
|
||||||
|
this.connection = connection;
|
||||||
|
this.userName = (userName == null || userName.isBlank())? USER_NONE : userName;
|
||||||
|
this.controller = controller;
|
||||||
|
}
|
||||||
|
|
||||||
|
public State getState() {
|
||||||
|
return this.state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setState (State newState) {
|
||||||
|
this.state = newState;
|
||||||
|
controller.stateChanged(newState);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run () {
|
||||||
|
startReceiving();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void startReceiving() {
|
||||||
|
System.out.println("Starting Connection Handler");
|
||||||
|
try {
|
||||||
|
System.out.println("Start receiving data...");
|
||||||
|
while (connection.isAvailable()) {
|
||||||
|
String data = connection.receive();
|
||||||
|
processData(data);
|
||||||
|
}
|
||||||
|
System.out.println("Stopped recieving data");
|
||||||
|
} catch (SocketException e) {
|
||||||
|
System.out.println("Connection terminated locally");
|
||||||
|
this.setState(DISCONNECTED);
|
||||||
|
System.err.println("Unregistered because connection terminated" + e.getMessage());
|
||||||
|
} catch (EOFException e) {
|
||||||
|
System.out.println("Connection terminated by remote");
|
||||||
|
this.setState(DISCONNECTED);
|
||||||
|
System.err.println("Unregistered because connection terminated" + e.getMessage());
|
||||||
|
} catch(IOException e) {
|
||||||
|
System.err.println("Communication error" + e);
|
||||||
|
} catch(ClassNotFoundException e) {
|
||||||
|
System.err.println("Received object of unknown type" + e.getMessage());
|
||||||
|
}
|
||||||
|
System.out.println("Stopped Connection Handler");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stopReceiving() {
|
||||||
|
System.out.println("Closing Connection Handler to Server");
|
||||||
|
try {
|
||||||
|
System.out.println("Stop receiving data...");
|
||||||
|
connection.close();
|
||||||
|
System.out.println("Stopped receiving data.");
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Failed to close connection." + e.getMessage());
|
||||||
|
}
|
||||||
|
System.out.println("Closed Connection Handler to Server");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void processData(String data) {
|
||||||
|
try {
|
||||||
|
// parse data content
|
||||||
|
Scanner scanner = new Scanner(data);
|
||||||
|
String sender = null;
|
||||||
|
String reciever = null;
|
||||||
|
String type = null;
|
||||||
|
String payload = null;
|
||||||
|
if (scanner.hasNextLine()) {
|
||||||
|
sender = scanner.nextLine();
|
||||||
|
} else {
|
||||||
|
throw new ChatProtocolException("No Sender found");
|
||||||
|
}
|
||||||
|
if (scanner.hasNextLine()) {
|
||||||
|
reciever = scanner.nextLine();
|
||||||
|
} else {
|
||||||
|
throw new ChatProtocolException("No Reciever found");
|
||||||
|
}
|
||||||
|
if (scanner.hasNextLine()) {
|
||||||
|
type = scanner.nextLine();
|
||||||
|
} else {
|
||||||
|
throw new ChatProtocolException("No Type found");
|
||||||
|
}
|
||||||
|
if (scanner.hasNextLine()) {
|
||||||
|
payload = scanner.nextLine();
|
||||||
|
}
|
||||||
|
// dispatch operation based on type parameter
|
||||||
|
if (type.equals(DATA_TYPE_CONNECT)) {
|
||||||
|
System.err.println("Illegal connect request from server");
|
||||||
|
} else if (type.equals(DATA_TYPE_CONFIRM)) {
|
||||||
|
if (state == CONFIRM_CONNECT) {
|
||||||
|
this.userName = reciever;
|
||||||
|
controller.setUserName(userName);
|
||||||
|
controller.setServerPort(connection.getRemotePort());
|
||||||
|
controller.setServerAddress(connection.getRemoteHost());
|
||||||
|
controller.addInfo(payload);
|
||||||
|
System.out.println("CONFIRM: " + payload);
|
||||||
|
this.setState(CONNECTED);
|
||||||
|
} else if (state == CONFIRM_DISCONNECT) {
|
||||||
|
controller.addInfo(payload);
|
||||||
|
System.out.println("CONFIRM: " + payload);
|
||||||
|
this.setState(DISCONNECTED);
|
||||||
|
} else {
|
||||||
|
System.err.println("Got unexpected confirm message: " + payload);
|
||||||
|
}
|
||||||
|
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
|
||||||
|
if (state == DISCONNECTED) {
|
||||||
|
System.out.println("DISCONNECT: Already in disconnected: " + payload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
controller.addInfo(payload);
|
||||||
|
System.out.println("DISCONNECT: " + payload);
|
||||||
|
this.setState(DISCONNECTED);
|
||||||
|
} else if (type.equals(DATA_TYPE_MESSAGE)) {
|
||||||
|
if (state != CONNECTED) {
|
||||||
|
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
controller.addMessage(sender, reciever, payload);
|
||||||
|
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
|
||||||
|
} else if (type.equals(DATA_TYPE_ERROR)) {
|
||||||
|
controller.addError(payload);
|
||||||
|
System.out.println("ERROR: " + payload);
|
||||||
|
} else {
|
||||||
|
System.out.println("Unknown data type received: " + type);
|
||||||
|
}
|
||||||
|
} catch (ChatProtocolException e) {
|
||||||
|
System.err.println("Error while processing data: " + e.getMessage());
|
||||||
|
sendData(USER_NONE, userName, DATA_TYPE_ERROR, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void sendData(String sender, String receiver, String type, String payload) {
|
||||||
|
if (connection.isAvailable()) {
|
||||||
|
new StringBuilder();
|
||||||
|
String data = new StringBuilder()
|
||||||
|
.append(sender+"\n")
|
||||||
|
.append(receiver+"\n")
|
||||||
|
.append(type+"\n")
|
||||||
|
.append(payload+"\n")
|
||||||
|
.toString();
|
||||||
|
try {
|
||||||
|
connection.send(data);
|
||||||
|
} catch (SocketException e) {
|
||||||
|
System.err.println("Connection closed: " + e.getMessage());
|
||||||
|
} catch (EOFException e) {
|
||||||
|
System.out.println("Connection terminated by remote");
|
||||||
|
} catch(IOException e) {
|
||||||
|
System.err.println("Communication error: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void connect() throws ChatProtocolException {
|
||||||
|
if (state != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
|
||||||
|
this.sendData(userName, USER_NONE, DATA_TYPE_CONNECT,null);
|
||||||
|
this.setState(CONFIRM_CONNECT);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void disconnect() throws ChatProtocolException {
|
||||||
|
if (state != NEW && state != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + state);
|
||||||
|
this.sendData(userName, USER_NONE, DATA_TYPE_DISCONNECT,null);
|
||||||
|
this.setState(CONFIRM_DISCONNECT);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void message(String receiver, String message) throws ChatProtocolException {
|
||||||
|
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state);
|
||||||
|
this.sendData(userName, receiver, DATA_TYPE_MESSAGE,message);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,51 @@
|
||||||
|
package ch.zhaw.pm2.multichat.client;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public class ClientMessageList {
|
||||||
|
private final List<MessageType> typeList = new ArrayList<>();
|
||||||
|
private final List<String> senderList = new ArrayList<>();
|
||||||
|
private final List<String> receiverList = new ArrayList<>();
|
||||||
|
private final List<String> messageList = new ArrayList<>();
|
||||||
|
private final ChatWindowController gui;
|
||||||
|
|
||||||
|
public ClientMessageList(ChatWindowController gui) {
|
||||||
|
this.gui = gui;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addMessage(MessageType type, String sender, String receiver, String message) {
|
||||||
|
typeList.add(type);
|
||||||
|
senderList.add(sender);
|
||||||
|
receiverList.add(receiver);
|
||||||
|
messageList.add(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void writeFilteredMessages(String filter) {
|
||||||
|
boolean showAll = filter == null || filter.isBlank();
|
||||||
|
gui.clearMessageArea();
|
||||||
|
for(int i=0; i<senderList.size(); i++) {
|
||||||
|
String sender = Objects.requireNonNullElse(senderList.get(i),"");
|
||||||
|
String receiver = Objects.requireNonNullElse(receiverList.get(i),"");
|
||||||
|
String message = Objects.requireNonNull(messageList.get(i), "");
|
||||||
|
if(showAll ||
|
||||||
|
sender.contains(filter) ||
|
||||||
|
receiver.contains(filter) ||
|
||||||
|
message.contains(filter))
|
||||||
|
{
|
||||||
|
switch (typeList.get(i)) {
|
||||||
|
case MESSAGE: gui.writeMessage(senderList.get(i), receiverList.get(i), messageList.get(i)); break;
|
||||||
|
case ERROR: gui.writeError(messageList.get(i)); break;
|
||||||
|
case INFO: gui.writeInfo(messageList.get(i)); break;
|
||||||
|
default: gui.writeError("Unexpected message type: " + typeList.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum MessageType {
|
||||||
|
INFO, MESSAGE, ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package ch.zhaw.pm2.multichat.client;
|
||||||
|
|
||||||
|
import javafx.application.Application;
|
||||||
|
import javafx.fxml.FXMLLoader;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.layout.Pane;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
|
||||||
|
public class ClientUI extends Application {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void start(Stage primaryStage) {
|
||||||
|
chatWindow(primaryStage);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void chatWindow(Stage primaryStage) {
|
||||||
|
try {
|
||||||
|
FXMLLoader loader = new FXMLLoader(getClass().getResource("ChatWindow.fxml"));
|
||||||
|
Pane rootPane = loader.load();
|
||||||
|
// fill in scene and stage setup
|
||||||
|
Scene scene = new Scene(rootPane);
|
||||||
|
//scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
|
||||||
|
|
||||||
|
// configure and show stage
|
||||||
|
primaryStage.setScene(scene);
|
||||||
|
primaryStage.setMinWidth(420);
|
||||||
|
primaryStage.setMinHeight(250);
|
||||||
|
primaryStage.setTitle("Multichat Client");
|
||||||
|
primaryStage.show();
|
||||||
|
} catch(Exception e) {
|
||||||
|
System.err.println("Error starting up UI" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,77 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
|
||||||
|
<?import javafx.geometry.*?>
|
||||||
|
<?import javafx.scene.control.*?>
|
||||||
|
<?import javafx.scene.layout.*?>
|
||||||
|
|
||||||
|
<BorderPane fx:id="rootPane" minWidth="-Infinity" prefHeight="500.0" prefWidth="420.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ch.zhaw.pm2.multichat.client.ChatWindowController">
|
||||||
|
<top>
|
||||||
|
<VBox BorderPane.alignment="CENTER">
|
||||||
|
<children>
|
||||||
|
<MenuBar>
|
||||||
|
<menus>
|
||||||
|
<Menu mnemonicParsing="false" text="Filter">
|
||||||
|
<items>
|
||||||
|
<MenuItem mnemonicParsing="false" text="press Enter">
|
||||||
|
<graphic>
|
||||||
|
<TextField fx:id="filterValue" onAction="#applyFilter" />
|
||||||
|
</graphic>
|
||||||
|
</MenuItem>
|
||||||
|
</items>
|
||||||
|
</Menu>
|
||||||
|
</menus>
|
||||||
|
</MenuBar>
|
||||||
|
<HBox fillHeight="false" spacing="5.0">
|
||||||
|
<children>
|
||||||
|
<TextField fx:id="userNameField" alignment="CENTER_RIGHT" maxWidth="1.7976931348623157E308" minWidth="110.0" promptText="Username" HBox.hgrow="SOMETIMES" />
|
||||||
|
<Label alignment="CENTER" contentDisplay="CENTER" text="\@" textAlignment="CENTER" textOverrun="CLIP" HBox.hgrow="NEVER">
|
||||||
|
<HBox.margin>
|
||||||
|
<Insets bottom="5.0" top="5.0" />
|
||||||
|
</HBox.margin>
|
||||||
|
</Label>
|
||||||
|
<TextField fx:id="serverAddressField" alignment="CENTER_RIGHT" minWidth="110.0" promptText="Host" HBox.hgrow="SOMETIMES" />
|
||||||
|
<Label text=":" HBox.hgrow="NEVER">
|
||||||
|
<HBox.margin>
|
||||||
|
<Insets bottom="5.0" top="5.0" />
|
||||||
|
</HBox.margin>
|
||||||
|
</Label>
|
||||||
|
<TextField fx:id="serverPortField" minWidth="-Infinity" prefWidth="60.0" promptText="Port" HBox.hgrow="NEVER" />
|
||||||
|
<Button fx:id="connectButton" maxWidth="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#toggleConnection" prefWidth="80.0" text="Connect" HBox.hgrow="NEVER">
|
||||||
|
<HBox.margin>
|
||||||
|
<Insets left="5.0" />
|
||||||
|
</HBox.margin>
|
||||||
|
</Button>
|
||||||
|
</children>
|
||||||
|
<BorderPane.margin>
|
||||||
|
<Insets />
|
||||||
|
</BorderPane.margin>
|
||||||
|
<padding>
|
||||||
|
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
|
||||||
|
</padding>
|
||||||
|
</HBox>
|
||||||
|
</children>
|
||||||
|
</VBox>
|
||||||
|
</top>
|
||||||
|
<bottom>
|
||||||
|
<HBox spacing="5.0">
|
||||||
|
<children>
|
||||||
|
<TextField fx:id="messageField" onAction="#message" HBox.hgrow="ALWAYS" />
|
||||||
|
<Button fx:id="sendButton" alignment="CENTER" maxWidth="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#message" prefWidth="50.0" text="Send" textAlignment="CENTER">
|
||||||
|
<HBox.margin>
|
||||||
|
<Insets left="5.0" />
|
||||||
|
</HBox.margin>
|
||||||
|
</Button>
|
||||||
|
</children>
|
||||||
|
<padding>
|
||||||
|
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
|
||||||
|
</padding>
|
||||||
|
</HBox>
|
||||||
|
</bottom>
|
||||||
|
<center>
|
||||||
|
<TextArea fx:id="messageArea" editable="false">
|
||||||
|
<BorderPane.margin>
|
||||||
|
<Insets left="5.0" right="5.0" />
|
||||||
|
</BorderPane.margin>
|
||||||
|
</TextArea>
|
||||||
|
</center>
|
||||||
|
</BorderPane>
|
|
@ -0,0 +1,7 @@
|
||||||
|
# Used to set properties for gradle builds
|
||||||
|
# (see https://dev.to/jmfayard/configuring-gradle-with-gradle-properties-211k)
|
||||||
|
|
||||||
|
# gradle configuration
|
||||||
|
# (https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties)
|
||||||
|
#org.gradle.warning.mode=(all,fail,summary,none) default: summary
|
||||||
|
org.gradle.warning.mode=all
|
Binary file not shown.
|
@ -0,0 +1,5 @@
|
||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
|
@ -0,0 +1,234 @@
|
||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015-2021 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||||
|
|
||||||
|
APP_NAME="Gradle"
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command;
|
||||||
|
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||||
|
# shell script including quotes and variable substitutions, so put them in
|
||||||
|
# double quotes to make sure that they get re-expanded; and
|
||||||
|
# * put everything else in single quotes, so that it's not re-expanded.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
org.gradle.wrapper.GradleWrapperMain \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
|
@ -0,0 +1,89 @@
|
||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%" == "" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%" == "" set DIRNAME=.
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if "%ERRORLEVEL%" == "0" goto execute
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
echo.
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
echo location of your Java installation.
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||||
|
echo.
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
echo location of your Java installation.
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
|
@ -0,0 +1,38 @@
|
||||||
|
/*
|
||||||
|
* Gradle build configuration for specific lab module / exercise
|
||||||
|
*/
|
||||||
|
// enabled plugins
|
||||||
|
plugins {
|
||||||
|
// Support for Java
|
||||||
|
id 'java'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Project/Module information
|
||||||
|
description = 'Uebung Multichat – Shared Protocol Classes'
|
||||||
|
group = 'ch.zhaw.pm2'
|
||||||
|
version = '2022.1'
|
||||||
|
|
||||||
|
// Dependency configuration
|
||||||
|
repositories {
|
||||||
|
// Use maven central for resolving dependencies.
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// Java plugin configuration
|
||||||
|
java {
|
||||||
|
// By default the Java version of the gradle process is used as source/target version.
|
||||||
|
// This can be overridden, to ensure a specific version. Enable only if required.
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17 // ensure Java source code compatibility
|
||||||
|
// targetCompatibility = JavaVersion.VERSION_17 // version of the created byte-code
|
||||||
|
|
||||||
|
// Java compiler specific options
|
||||||
|
compileJava {
|
||||||
|
// source files should be UTF-8 encoded
|
||||||
|
options.encoding = 'UTF-8'
|
||||||
|
// for more options see https://docs.gradle.org/current/dsl/org.gradle.api.tasks.compile.CompileOptions.html
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package ch.zhaw.pm2.multichat.protocol;
|
||||||
|
|
||||||
|
public class ChatProtocolException extends Exception {
|
||||||
|
|
||||||
|
public ChatProtocolException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ChatProtocolException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ChatProtocolException(Throwable cause) {
|
||||||
|
super(cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,390 @@
|
||||||
|
package ch.zhaw.pm2.multichat.protocol;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper class to support simple network communication.
|
||||||
|
* It provides access to the two subclasses:
|
||||||
|
* <ul>
|
||||||
|
* <li>{@link NetworkServer} is used on the server side to open a port and wait for connection request from clients</li>
|
||||||
|
* <li>{@link NetworkConnection} represents a bidirectional connection between client and server, to send and
|
||||||
|
* receive Objects</li>
|
||||||
|
* </ul>
|
||||||
|
* <p>The typical process works as follows</p>
|
||||||
|
* <ul>
|
||||||
|
* <li>The server creates a {@link NetworkServer} instance using the factory method
|
||||||
|
* {@link NetworkHandler#createServer(int port)}. This creates and opens a port (range: 0 - 65535)
|
||||||
|
* on all available interfaces (IP-networks, incl. localhost loopback) of the current host.</li>
|
||||||
|
* <li>As soon the server is ready to receive requests it calls the method {@link NetworkServer#waitForConnection()}
|
||||||
|
* which is blocking and waiting for client to open a connection.</li>
|
||||||
|
* <li>On the client side, a new {@link NetworkConnection} instance is created to connect to the server using the
|
||||||
|
* factory method {@link NetworkHandler#openConnection(String host, int port)}, which opens a connection to the
|
||||||
|
* given host (domainname or ip-address) on the specified server port</li>
|
||||||
|
* <li>On the server side, the waiting method {@link NetworkServer#waitForConnection()} returns an instance of
|
||||||
|
* {@link NetworkConnection} which represents the specific connection to the calling client.</li>
|
||||||
|
* <li>This connection can be used to send and receive data between server and client.</li>
|
||||||
|
* <li>On the server side, the handling of each interaction ('session') with a specific client should be handled in
|
||||||
|
* a separate {@link Thread}, after starting the thread, the server can go back and wait for the next connection
|
||||||
|
* request.</li>
|
||||||
|
* <li>Both sides (server & client) need to handle sending and receiving of data separately
|
||||||
|
* <ul>
|
||||||
|
* <li>reading data: call {@link NetworkConnection#receive()}, which is blocking until a data object is
|
||||||
|
* received. As soon the object has been received, the method returns an instance of the object.
|
||||||
|
* This object (request) can be processed (on the server side, usually a response is sent back;
|
||||||
|
* on the client side, usually the result is displayed to the user). After processing is finished the
|
||||||
|
* process calls {@link NetworkConnection#receive()} again to wait for the next request.
|
||||||
|
* </li>
|
||||||
|
* <li>sending data: call {@link NetworkConnection#send(Serializable data)}, which sends the given data
|
||||||
|
* object to the remote side. The method returns as soon the object has been transmitted.
|
||||||
|
* <b>Important: {@link NetworkConnection} is not thread safe</b>, therefore make sure that only one thread
|
||||||
|
* at a time is sending data.</li>
|
||||||
|
* </ul>
|
||||||
|
* <b>Important:Sending and receiving of data is completely asynchronous and can happen in parallel.</b>
|
||||||
|
* </li>
|
||||||
|
* <li>The connection stays open until one of the peers decides to close it using {@link NetworkConnection#close()}.
|
||||||
|
* In this case, all waiting method calls (e.g. {@link NetworkConnection#receive()} on the opposite side are
|
||||||
|
* interrupted and a {@link EOFException} is thrown.<br>
|
||||||
|
* On the local side, waiting method calls (threads) are also interrupted and a {@link java.net.SocketException}
|
||||||
|
* is thrown.</li>
|
||||||
|
* <li>To stop receiving new connection requests on the server side, the server may call
|
||||||
|
* {@link NetworkServer#close()} which will close all currently open {@link NetworkConnection} objects.</li>
|
||||||
|
* </ul>
|
||||||
|
* <p>{@link NetworkServer} and {@link NetworkConnection} are typed using generics. This means, when creating an
|
||||||
|
* instance it has to be specified, what types of objects can be sent between server and client. The type has to be
|
||||||
|
* identical on both sides of the connection. These Objects have to be of type {@link Serializable}, which is a
|
||||||
|
* marker interface specifying that an object can be serialized/deserialized. As long all properties within a
|
||||||
|
* class are also Serializable, your class simply can be marked using it. All standard Java data-types are by default
|
||||||
|
* Serializable.</p>
|
||||||
|
*/
|
||||||
|
public class NetworkHandler {
|
||||||
|
/**
|
||||||
|
* Default network address used to open a connection to: localhost (domainname), 127.0.0.1 (IPv4), ::1 (IPv6)
|
||||||
|
*/
|
||||||
|
public static final InetAddress DEFAULT_ADDRESS = InetAddress.getLoopbackAddress();
|
||||||
|
/**
|
||||||
|
* Default port on the server side to listen for requests
|
||||||
|
*/
|
||||||
|
public static final int DEFAULT_PORT = 22243;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* private Constructor to avoid initialization.
|
||||||
|
* Use the static factory methods to create {@link NetworkServer} or {@link NetworkConnection} instances.
|
||||||
|
*/
|
||||||
|
private NetworkHandler() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an instance of a {@link NetworkServer} listening on the specified port for connection request for
|
||||||
|
* Objects of type T.
|
||||||
|
* @param port port to open on the server host (range: 1 - 65535)
|
||||||
|
* @param <T> type of the Objects to be transmitted in the created {@link NetworkConnection}
|
||||||
|
* @return {@link NetworkServer} object to be used to wait for connections.
|
||||||
|
* @throws IOException if an error occured opening the port, e.g. the port number is already used.
|
||||||
|
*/
|
||||||
|
public static <T extends Serializable> NetworkServer<T> createServer(int port) throws IOException {
|
||||||
|
return new NetworkServer<>(port);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an instance of a {@link NetworkServer} listening on the default port (22243) for connection request for
|
||||||
|
* Objects of type T.
|
||||||
|
* @param <T> type of the Objects to be transmitted in the created {@link NetworkConnection}
|
||||||
|
* @return {@link NetworkServer} object to be used to wait for connections.
|
||||||
|
* @throws IOException if an error occured opening the port, e.g. the port number is already used.
|
||||||
|
*/
|
||||||
|
public static <T extends Serializable> NetworkServer<T> createServer() throws IOException {
|
||||||
|
return new NetworkServer<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an instance of a {@link NetworkConnection} connecting to the specified host/port to send and receive
|
||||||
|
* objects of type T.
|
||||||
|
* @param address {@link InetAddress} object for the host
|
||||||
|
* @param port port number the server is waiting for connection requests
|
||||||
|
* @param <T> type of Objects to be transmitted trough this connection
|
||||||
|
* @return {@link NetworkConnection} object representing the bidirectional channel between client and server.
|
||||||
|
* @throws IOException if an error occurred opening the connection, e.g. server is not responding.
|
||||||
|
*/
|
||||||
|
public static <T extends Serializable> NetworkConnection<T> openConnection(InetAddress address, int port)
|
||||||
|
throws IOException
|
||||||
|
{
|
||||||
|
Socket socket = new Socket(address, port);
|
||||||
|
socket.setKeepAlive(true);
|
||||||
|
return new NetworkConnection<>(socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an instance of a {@link NetworkConnection} connecting to the specified host/port to send and receive
|
||||||
|
* objects of type T.
|
||||||
|
* @param hostname server host name or address in String representation (e.g. "www.zhaw.ch", "160.85.104.112")
|
||||||
|
* @param port port number the server is waiting for connection requests
|
||||||
|
* @param <T> type of Objects to be transmitted trough this connection
|
||||||
|
* @return {@link NetworkConnection} object representing the bidirectional channel between client and server.
|
||||||
|
* @throws IOException if an error occurred opening the connection, e.g. server is not responding.
|
||||||
|
*/
|
||||||
|
public static <T extends Serializable> NetworkConnection<T> openConnection(String hostname, int port)
|
||||||
|
throws IOException
|
||||||
|
{
|
||||||
|
return openConnection(InetAddress.getByName(hostname), port);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an instance of a {@link NetworkConnection} connecting to the default host ("localhost",127.0.0.1,::1)
|
||||||
|
* and port (22243) to send and receive objects of type T.
|
||||||
|
* @param <T> type of Objects to be transmitted trough this connection
|
||||||
|
* @return {@link NetworkConnection} object representing the bidirectional channel between client and server.
|
||||||
|
* @throws IOException if an error occurred opening the connection, e.g. server is not responding.
|
||||||
|
*/
|
||||||
|
public static <T extends Serializable> NetworkConnection<T> openConnection()
|
||||||
|
throws IOException
|
||||||
|
{
|
||||||
|
return openConnection(DEFAULT_ADDRESS, DEFAULT_PORT);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Network communication class used on the server side to handle connection request from clients.
|
||||||
|
* The class opens a port on the server host and allows the server process to wait for connection requests.
|
||||||
|
* As soon a request comes in a {@link NetworkConnection} object is created, which is used to handle all the
|
||||||
|
* communication between the two peers.
|
||||||
|
* @param <T> type of the Objects to be transmitted in the created {@link NetworkConnection}
|
||||||
|
*/
|
||||||
|
public static class NetworkServer<T extends Serializable> implements Closeable {
|
||||||
|
private final ServerSocket serverSocket;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <b>Private constructor: use {@link NetworkHandler#createServer(int port)} factory method to create an instance</b>
|
||||||
|
* Open a server port an the given port number. The port number must be unique (i.e. not used by another process)
|
||||||
|
* @param port port number (range: 1 - 65535) to open to wait for requests.
|
||||||
|
* @throws IOException if an error occurred opening the port, e.g. the port number is already used.
|
||||||
|
*/
|
||||||
|
private NetworkServer(int port) throws IOException {
|
||||||
|
this.serverSocket = new ServerSocket(port);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <b>Private constructor: use {@link NetworkHandler#createServer(int port)} factory method to create an instance</b>
|
||||||
|
* Open a server port an the default port (22243).
|
||||||
|
* @throws IOException if an error occurred opening the port, e.g. the port number is already used.
|
||||||
|
*/
|
||||||
|
private NetworkServer() throws IOException {
|
||||||
|
this(DEFAULT_PORT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Blocks the current thread and waits for connection requests on the declared port of the
|
||||||
|
* {@link NetworkServer} object. Returns a {@link NetworkConnection} object representing the connection to a
|
||||||
|
* client if a successfull connection has been established.
|
||||||
|
* @return {@link NetworkConnection} object representing the connection to the connecting client.
|
||||||
|
* @throws IOException if an error occurred while waiting (e.g. throws a {@link java.net.SocketException} if
|
||||||
|
* the port has been closed using the {@link NetworkServer#close()} method.
|
||||||
|
*/
|
||||||
|
public NetworkConnection<T> waitForConnection() throws IOException {
|
||||||
|
Socket socket = serverSocket.accept();
|
||||||
|
socket.setKeepAlive(true);
|
||||||
|
return new NetworkConnection<>(socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does indicate if the server is ready and bound to the declared port.
|
||||||
|
* @return true if the server is ready and bound to the declared port, false otherwise
|
||||||
|
*/
|
||||||
|
public boolean isAvailable() {
|
||||||
|
return serverSocket != null && serverSocket.isBound();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does indicate if the server has been closed. A closed server can not be reopened. To reopen a port, a
|
||||||
|
* new Instance must be created.
|
||||||
|
* @return true if the server is closed, false otherwise.
|
||||||
|
*/
|
||||||
|
public boolean isClosed() {
|
||||||
|
return serverSocket == null || serverSocket.isClosed();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the port number on which the server is listening for requests.
|
||||||
|
* @return returns the port number (range: 1 - 65535) if the server is available, 0 otherwise.
|
||||||
|
*/
|
||||||
|
public int getHostPort() {
|
||||||
|
return isAvailable()? serverSocket.getLocalPort() : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the host address in String format on which the server is listening for requests.
|
||||||
|
* @return host address in String format or "unbound" if not available.
|
||||||
|
*/
|
||||||
|
public String getHostAddress() {
|
||||||
|
return isAvailable()? serverSocket.getInetAddress().getHostAddress() : "unbound";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Closes this Server and releases any system resources associated with it.
|
||||||
|
* Closing the Server, closes also all {@link NetworkConnection} objects created by the server and throws a
|
||||||
|
* {@link java.net.SocketException} on all blocking calls (e.g. {@link NetworkServer#waitForConnection()})
|
||||||
|
* on the server.
|
||||||
|
* If the Server is already closed then invoking this method has no effect.
|
||||||
|
*
|
||||||
|
* @throws IOException if an I/O error occurs
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void close() throws IOException {
|
||||||
|
if (serverSocket != null && !serverSocket.isClosed()) {
|
||||||
|
serverSocket.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
NetworkServer<?> that = (NetworkServer<?>) o;
|
||||||
|
return serverSocket.equals(that.serverSocket);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(serverSocket);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Network communication class representing a bidirectional connection between two peers (client and server),
|
||||||
|
* to send and receive Objects of type T.
|
||||||
|
* The client can open a new connection using the factory method
|
||||||
|
* {@link NetworkHandler#openConnection(String hostname, int port)} to connect to the specified server.
|
||||||
|
* On the server side, the {@link NetworkServer#waitForConnection()} method is creating a matching instance for the
|
||||||
|
* connecting client.
|
||||||
|
*
|
||||||
|
* <li>On an open connection, both sides (server & client) need to handle sending and receiving of data separately
|
||||||
|
* <ul>
|
||||||
|
* <li>reading data: call {@link NetworkConnection#receive()}, which is blocking until a data object is
|
||||||
|
* received. As soon the object has been received, the method returns an instance of the object.
|
||||||
|
* This object (request) can be processed (on the server side, usually a response is sent back;
|
||||||
|
* on the client side, usually the result is displayed to the user). After processing is finished the
|
||||||
|
* process calls {@link NetworkConnection#receive()} again to wait for the next request.
|
||||||
|
* </li>
|
||||||
|
* <li>sending data: call {@link NetworkConnection#send(Serializable data)}, which sends the given data
|
||||||
|
* object to the remote side. The method returns as soon the object has been transmitted.
|
||||||
|
* <b>Important: {@link NetworkConnection} is not thread safe</b>, therefore make sure that only one thread
|
||||||
|
* at a time is sending data.
|
||||||
|
* </li>
|
||||||
|
* </ul>
|
||||||
|
* <p><b>Important: Sending and receiving of data is completely asynchronous and can happen in parallel.</b>
|
||||||
|
* The connection stays open until one of the peers decides to close it using {@link NetworkConnection#close()}.<br>
|
||||||
|
* In this case, all waiting method calls (e.g. {@link NetworkConnection#receive()} on the opposite side are
|
||||||
|
* interrupted and a {@link EOFException} is thrown.<br>
|
||||||
|
* On the local side, waiting method calls (threads) are also interrupted and a {@link java.net.SocketException}
|
||||||
|
* is thrown.</p>
|
||||||
|
*
|
||||||
|
* @param <T> type of Objects to be transmitted trough this connection
|
||||||
|
*/
|
||||||
|
public static class NetworkConnection<T extends Serializable> implements Closeable {
|
||||||
|
private final Socket socket;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <b>Privat constructor: Use {@link NetworkHandler#openConnection(String hostname, int port)} and similar
|
||||||
|
* factory methods to create instances of {@link NetworkConnection}</b>
|
||||||
|
* @param socket operating system socket to use for the communication.
|
||||||
|
*/
|
||||||
|
private NetworkConnection(Socket socket) {
|
||||||
|
this.socket = socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to send data to the opposite side. The call is sending out the requests immediately and returns if
|
||||||
|
* submitted successfully. Data can also be sent, while another thread is waiting for requests, but it has
|
||||||
|
* to be made sure that only one thread is sending data at a time (not thread-safe).
|
||||||
|
* If an error occurs a {@link IOException} is thrown.
|
||||||
|
* @param data data object of type T to be submitted through the connection.
|
||||||
|
* @throws IOException if an error occurs (e.g. connection interrupted while sending, ...)
|
||||||
|
*/
|
||||||
|
public void send(T data) throws IOException {
|
||||||
|
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
|
||||||
|
outputStream.writeObject(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to receive data from the opposite side. The call is blocking until a requests comes in, and the
|
||||||
|
* transferred object is returned.
|
||||||
|
* If the connection is closed during waiting, a {@link java.net.SocketException} is thrown, if the close
|
||||||
|
* was initiated locally or {@link EOFException} is thrown if the connection is closed from the remote side.
|
||||||
|
* Other {@link IOException} may be thrown on any another communication error.
|
||||||
|
* @return data object of type T received through the connection.
|
||||||
|
* @throws IOException if an error occours. (e.g. terminated locally/remotely) see above.
|
||||||
|
* @throws ClassNotFoundException if the data object received does not match any class in the local classpath
|
||||||
|
*/
|
||||||
|
public T receive() throws IOException, ClassNotFoundException {
|
||||||
|
ObjectInputStream inputStream = new ObjectInputStream(this.socket.getInputStream());
|
||||||
|
return (T) inputStream.readObject();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates if the connection is open and connected to the peer.
|
||||||
|
* @return true if the connection is open and connected, false otherwise
|
||||||
|
*/
|
||||||
|
public boolean isAvailable() {
|
||||||
|
return !isClosed() && socket.isConnected();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicate if the connection has been closed. A closed connection can not be reopened.
|
||||||
|
* To re-open, a new Instance must be created.
|
||||||
|
* @return true if the connection is closed, false otherwise.
|
||||||
|
*/
|
||||||
|
public boolean isClosed() {
|
||||||
|
return socket == null || socket.isClosed();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the port number of the remote host, if the connection is available.
|
||||||
|
* @return port number (range: 1 - 65535) of the port on the remote host, 0 if not connected.
|
||||||
|
*/
|
||||||
|
public int getRemotePort() {
|
||||||
|
return isAvailable()? socket.getPort() : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the host name of the remote peer. If available looks up the hostname (e.g. "www.zhaw.ch"),
|
||||||
|
* otherwise returns a string representation of the IP address (e.g. "160.85.104.112").
|
||||||
|
* @return host name of the remote peer, "not connected" if connection is not available.
|
||||||
|
*/
|
||||||
|
public String getRemoteHost() {
|
||||||
|
return isAvailable()? socket.getInetAddress().getHostName() : "not connected";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Closes this NetworkConnection and releases any system resources associated with it.
|
||||||
|
* If the connection is closed a {@link java.net.SocketException} is thrown on all local waiting threads
|
||||||
|
* (e.g. in {@link NetworkConnection#receive()}), and on the remote side an {@link EOFException} is thrown
|
||||||
|
* on all waiting threads.
|
||||||
|
* If the connection is already closed then invoking this method has no effect.
|
||||||
|
* @throws IOException if an I/O error occurs
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void close() throws IOException {
|
||||||
|
if (!isClosed()) {
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
NetworkConnection<?> that = (NetworkConnection<?>) o;
|
||||||
|
return socket.equals(that.socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(socket);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,58 @@
|
||||||
|
/*
|
||||||
|
* Gradle build configuration for specific lab module / exercise
|
||||||
|
*/
|
||||||
|
// enabled plugins
|
||||||
|
plugins {
|
||||||
|
// Support for Java
|
||||||
|
id 'java'
|
||||||
|
// Support for Java applications
|
||||||
|
id 'application'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Project/Module information
|
||||||
|
description = 'Uebung Multichat – Server'
|
||||||
|
group = 'ch.zhaw.pm2'
|
||||||
|
version = '2022.1'
|
||||||
|
|
||||||
|
// Dependency configuration
|
||||||
|
repositories {
|
||||||
|
// Use maven central for resolving dependencies.
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// dependency to the protocol library
|
||||||
|
implementation project(':protocol')
|
||||||
|
// JUnit Jupiter dependencies
|
||||||
|
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.+'
|
||||||
|
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.+'
|
||||||
|
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.+'
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configuration for Application plugin
|
||||||
|
application {
|
||||||
|
// Define the main class for the application.
|
||||||
|
mainClass = 'ch.zhaw.pm2.multichat.server.Server'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test task configuration
|
||||||
|
test {
|
||||||
|
// Use JUnit platform for unit tests
|
||||||
|
useJUnitPlatform()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Java plugin configuration
|
||||||
|
java {
|
||||||
|
// By default the Java version of the gradle process is used as source/target version.
|
||||||
|
// This can be overridden, to ensure a specific version. Enable only if required.
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17 // ensure Java source code compatibility
|
||||||
|
// targetCompatibility = JavaVersion.VERSION_17 // version of the created byte-code
|
||||||
|
|
||||||
|
// Java compiler specific options
|
||||||
|
compileJava {
|
||||||
|
// source files should be UTF-8 encoded
|
||||||
|
options.encoding = 'UTF-8'
|
||||||
|
// for more options see https://docs.gradle.org/current/dsl/org.gradle.api.tasks.compile.CompileOptions.html
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,96 @@
|
||||||
|
package ch.zhaw.pm2.multichat.server;
|
||||||
|
|
||||||
|
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.SocketException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
|
||||||
|
public class Server {
|
||||||
|
|
||||||
|
// Server connection
|
||||||
|
private NetworkHandler.NetworkServer<String> networkServer;
|
||||||
|
|
||||||
|
// Connection registry
|
||||||
|
private Map<String,ServerConnectionHandler> connections = new HashMap<>();
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// Parse arguments for server port.
|
||||||
|
try {
|
||||||
|
int port;
|
||||||
|
switch (args.length) {
|
||||||
|
case 0 -> port = NetworkHandler.DEFAULT_PORT;
|
||||||
|
case 1 -> port = Integer.parseInt(args[0]);
|
||||||
|
default -> {
|
||||||
|
System.out.println("Illegal number of arguments: [<ServerPort>]");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Initialize server
|
||||||
|
final Server server = new Server(port);
|
||||||
|
|
||||||
|
// This adds a shutdown hook running a cleanup task if the JVM is terminated (kill -HUP, Ctrl-C,...)
|
||||||
|
Runtime.getRuntime().addShutdownHook(new Thread() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
try {
|
||||||
|
Thread.sleep(200);
|
||||||
|
System.out.println("Shutdown initiated...");
|
||||||
|
server.terminate();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
System.out.println("Warning: Shutdown interrupted. " + e);
|
||||||
|
} finally {
|
||||||
|
System.out.println("Shutdown complete.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start server
|
||||||
|
server.start();
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Error while starting server." + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Server(int serverPort) throws IOException {
|
||||||
|
// Open server connection
|
||||||
|
System.out.println("Create server connection");
|
||||||
|
networkServer = NetworkHandler.createServer(serverPort);
|
||||||
|
System.out.println("Listening on " + networkServer.getHostAddress() + ":" + networkServer.getHostPort());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void start() {
|
||||||
|
System.out.println("Server started.");
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection();
|
||||||
|
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections);
|
||||||
|
connectionHandler.startReceiving();
|
||||||
|
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
|
||||||
|
connectionHandler.getUserName(),
|
||||||
|
connection.getRemoteHost(),
|
||||||
|
connection.getRemotePort()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} catch(SocketException e) {
|
||||||
|
System.out.println("Server connection terminated");
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
System.err.println("Communication error " + e);
|
||||||
|
}
|
||||||
|
// close server
|
||||||
|
System.out.println("Server Stopped.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void terminate() {
|
||||||
|
try {
|
||||||
|
System.out.println("Close server port.");
|
||||||
|
networkServer.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Failed to close server connection: " + e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,183 @@
|
||||||
|
package ch.zhaw.pm2.multichat.server;
|
||||||
|
|
||||||
|
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
||||||
|
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||||
|
|
||||||
|
import java.io.EOFException;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.SocketException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Scanner;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
|
||||||
|
|
||||||
|
public class ServerConnectionHandler {
|
||||||
|
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
|
||||||
|
private final int connectionId = connectionCounter.incrementAndGet();
|
||||||
|
private final NetworkHandler.NetworkConnection<String> connection;
|
||||||
|
private final Map<String,ServerConnectionHandler> connectionRegistry;
|
||||||
|
|
||||||
|
// Data types used for the Chat Protocol
|
||||||
|
private static final String DATA_TYPE_CONNECT = "CONNECT";
|
||||||
|
private static final String DATA_TYPE_CONFIRM = "CONFIRM";
|
||||||
|
private static final String DATA_TYPE_DISCONNECT = "DISCONNECT";
|
||||||
|
private static final String DATA_TYPE_MESSAGE = "MESSAGE";
|
||||||
|
private static final String DATA_TYPE_ERROR = "ERROR";
|
||||||
|
|
||||||
|
private static final String USER_NONE = "";
|
||||||
|
private static final String USER_ALL = "*";
|
||||||
|
|
||||||
|
private String userName = "Anonymous-"+connectionId;
|
||||||
|
private State state = NEW;
|
||||||
|
|
||||||
|
enum State {
|
||||||
|
NEW, CONNECTED, DISCONNECTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
||||||
|
Map<String,ServerConnectionHandler> registry) {
|
||||||
|
Objects.requireNonNull(connection, "Connection must not be null");
|
||||||
|
Objects.requireNonNull(registry, "Registry must not be null");
|
||||||
|
this.connection = connection;
|
||||||
|
this.connectionRegistry = registry;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUserName() {
|
||||||
|
return this.userName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void startReceiving() {
|
||||||
|
System.out.println("Starting Connection Handler for " + userName);
|
||||||
|
try {
|
||||||
|
System.out.println("Start receiving data...");
|
||||||
|
while (connection.isAvailable()) {
|
||||||
|
String data = connection.receive();
|
||||||
|
processData(data);
|
||||||
|
}
|
||||||
|
System.out.println("Stopped recieving data");
|
||||||
|
} catch (SocketException e) {
|
||||||
|
System.out.println("Connection terminated locally");
|
||||||
|
connectionRegistry.remove(userName);
|
||||||
|
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
|
||||||
|
} catch (EOFException e) {
|
||||||
|
System.out.println("Connection terminated by remote");
|
||||||
|
connectionRegistry.remove(userName);
|
||||||
|
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
|
||||||
|
} catch(IOException e) {
|
||||||
|
System.err.println("Communication error: " + e);
|
||||||
|
} catch(ClassNotFoundException e) {
|
||||||
|
System.err.println("Received object of unknown type: " + e.getMessage());
|
||||||
|
}
|
||||||
|
System.out.println("Stopping Connection Handler for " + userName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stopReceiving() {
|
||||||
|
System.out.println("Closing Connection Handler for " + userName);
|
||||||
|
try {
|
||||||
|
System.out.println("Stop receiving data...");
|
||||||
|
connection.close();
|
||||||
|
System.out.println("Stopped receiving data.");
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Failed to close connection." + e);
|
||||||
|
}
|
||||||
|
System.out.println("Closed Connection Handler for " + userName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void processData(String data) {
|
||||||
|
try {
|
||||||
|
// parse data content
|
||||||
|
Scanner scanner = new Scanner(data);
|
||||||
|
String sender = null;
|
||||||
|
String reciever = null;
|
||||||
|
String type = null;
|
||||||
|
String payload = null;
|
||||||
|
if (scanner.hasNextLine()) {
|
||||||
|
sender = scanner.nextLine();
|
||||||
|
} else {
|
||||||
|
throw new ChatProtocolException("No Sender found");
|
||||||
|
}
|
||||||
|
if (scanner.hasNextLine()) {
|
||||||
|
reciever = scanner.nextLine();
|
||||||
|
} else {
|
||||||
|
throw new ChatProtocolException("No Reciever found");
|
||||||
|
}
|
||||||
|
if (scanner.hasNextLine()) {
|
||||||
|
type = scanner.nextLine();
|
||||||
|
} else {
|
||||||
|
throw new ChatProtocolException("No Type found");
|
||||||
|
}
|
||||||
|
if (scanner.hasNextLine()) {
|
||||||
|
payload = scanner.nextLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
// dispatch operation based on type parameter
|
||||||
|
if (type.equals(DATA_TYPE_CONNECT)) {
|
||||||
|
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
|
||||||
|
if (sender == null || sender.isBlank()) sender = this.userName;
|
||||||
|
if (connectionRegistry.containsKey(sender))
|
||||||
|
throw new ChatProtocolException("User name already taken: " + sender);
|
||||||
|
this.userName = sender;
|
||||||
|
connectionRegistry.put(userName, this);
|
||||||
|
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Registration successfull for " + userName);
|
||||||
|
this.state = CONNECTED;
|
||||||
|
} else if (type.equals(DATA_TYPE_CONFIRM)) {
|
||||||
|
System.out.println("Not expecting to receive a CONFIRM request from client");
|
||||||
|
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
|
||||||
|
if (state == DISCONNECTED)
|
||||||
|
throw new ChatProtocolException("Illegal state for disconnect request: " + state);
|
||||||
|
if (state == CONNECTED) {
|
||||||
|
connectionRegistry.remove(this.userName);
|
||||||
|
}
|
||||||
|
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Confirm disconnect of " + userName);
|
||||||
|
this.state = DISCONNECTED;
|
||||||
|
this.stopReceiving();
|
||||||
|
} else if (type.equals(DATA_TYPE_MESSAGE)) {
|
||||||
|
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state);
|
||||||
|
if (USER_ALL.equals(reciever)) {
|
||||||
|
for (ServerConnectionHandler handler : connectionRegistry.values()) {
|
||||||
|
handler.sendData(sender, reciever, type, payload);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ServerConnectionHandler handler = connectionRegistry.get(reciever);
|
||||||
|
if (handler != null) {
|
||||||
|
handler.sendData(sender, reciever, type, payload);
|
||||||
|
} else {
|
||||||
|
this.sendData(USER_NONE, userName, DATA_TYPE_ERROR, "Unknown User: " + reciever);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (type.equals(DATA_TYPE_ERROR)) {
|
||||||
|
System.err.println("Received error from client (" + sender + "): " + payload);
|
||||||
|
} else {
|
||||||
|
System.err.println("Unknown data type received: " + type);
|
||||||
|
|
||||||
|
}
|
||||||
|
} catch(ChatProtocolException e) {
|
||||||
|
System.out.println("Error while processing data" + e.getMessage());
|
||||||
|
sendData(USER_NONE, userName, DATA_TYPE_ERROR, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void sendData(String sender, String receiver, String type, String payload) {
|
||||||
|
if (connection.isAvailable()) {
|
||||||
|
new StringBuilder();
|
||||||
|
String data = new StringBuilder()
|
||||||
|
.append(sender+"\n")
|
||||||
|
.append(receiver+"\n")
|
||||||
|
.append(type+"\n")
|
||||||
|
.append(payload+"\n")
|
||||||
|
.toString();
|
||||||
|
try {
|
||||||
|
connection.send(data);
|
||||||
|
} catch (SocketException e) {
|
||||||
|
System.out.println("Connection closed: " + e.getMessage());
|
||||||
|
} catch (EOFException e) {
|
||||||
|
System.out.println("Connection terminated by remote");
|
||||||
|
} catch(IOException e) {
|
||||||
|
System.out.println("Communication error: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
/*
|
||||||
|
* This file was generated by the Gradle 'init' task.
|
||||||
|
*
|
||||||
|
* The settings file is used to specify which projects to include in your build.
|
||||||
|
*
|
||||||
|
* Detailed information about configuring a multi-project build in Gradle can be found
|
||||||
|
* in the user manual at https://docs.gradle.org/6.1/userguide/multi_project_builds.html
|
||||||
|
*/
|
||||||
|
|
||||||
|
rootProject.name = 'multichat'
|
||||||
|
include 'protocol'
|
||||||
|
include 'server'
|
||||||
|
include 'client'
|
Loading…
Reference in New Issue