Compare commits

..
Author SHA1 Message Date
Andrin Fassbind 5a26c6b127 create setConnection in ConnectionHandlerClass 2022-04-14 21:37:06 +02:00
Andrin Fassbind 5e6e9d5817 Create ConnectionHandlerClass
Remove Codeduplication
2022-04-14 21:11:58 +02:00
fassbandandGitHub Enterprise af46e499ff Merge pull request #34 from PM2-IT21bWIN-ruiz-mach-krea/Fix_WindowCloseHandler
fixed Disconnecting when window is closed
2022-04-14 19:36:26 +02:00
schrom01 8c588ee75c fixed Disconnecting when window is closed
#6
2022-04-14 19:13:21 +02:00
Roman SchenkandGitHub Enterprise 800528cc37 Merge pull request #33 from PM2-IT21bWIN-ruiz-mach-krea/Server_Console_Display
fixes Issue #20
2022-04-14 16:02:06 +02:00
Leonardo Brandenberger 886d9e5e43 fixes #20 2022-04-14 06:55:10 +02:00
fassbandandGitHub Enterprise 7c68472859 Merge pull request #32 from PM2-IT21bWIN-ruiz-mach-krea/Fixing_private_Messages
fixed Problem "private Messages are visible for sender"
2022-04-13 17:35:48 +02:00
Roman SchenkandGitHub Enterprise b9ffb2b133 Update ServerConnectionHandler.java
added Commment for documentation.
2022-04-13 17:35:07 +02:00
schrom01 e69ced4081 fixed Problem "private Messages are visible for sender"
#28
2022-04-13 17:24:22 +02:00
Roman SchenkandGitHub Enterprise d1dfe6c1ab Merge pull request #31 from PM2-IT21bWIN-ruiz-mach-krea/Remove_Controller_From_Handler
Remove ChatWindowController from ClientConnectionHandler
2022-04-13 16:13:33 +02:00
Andrin Fassbind 3eedf58685 Remove ChatWindowController from ClientConnectionHandler
Make ChatWindowController listen for message changes

fixed Issue #23
2022-04-13 15:55:08 +02:00
Andrin Fassbind 1777b62582 Make State in ClientConnectionHandler property
Add change listener for stateproperty in ChatWindowController

fixed Issue #21
2022-04-13 15:03:07 +02:00
Roman SchenkandGitHub Enterprise a0b7b363c3 Merge pull request #30 from PM2-IT21bWIN-ruiz-mach-krea/Server_Console_Display
fixed issue #5
2022-04-12 21:35:26 +02:00
Leonardo Brandenberger 914fa8f1e2 fixed #5 2022-04-12 16:42:19 +02:00
7 changed files with 261 additions and 238 deletions
@@ -1,12 +1,12 @@
package ch.zhaw.pm2.multichat.client; package ch.zhaw.pm2.multichat.client;
import ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State; import ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException; import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler; import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.beans.value.ChangeListener; import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue; import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.event.EventHandler; import javafx.event.EventHandler;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.control.Button; import javafx.scene.control.Button;
@@ -16,10 +16,8 @@ import javafx.scene.layout.Pane;
import javafx.stage.WindowEvent; import javafx.stage.WindowEvent;
import java.io.IOException; import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*; import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
public class ChatWindowController { public class ChatWindowController {
private ClientConnectionHandler connectionHandler; private ClientConnectionHandler connectionHandler;
@@ -42,23 +40,20 @@ public class ChatWindowController {
public void initialize() { public void initialize() {
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName()); serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT)); serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT));
this.messages = new ClientMessageList();
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
setMessageField(messages.getMessages());
} }
});
public void setMessages(ClientMessageList messages) {
this.messages = messages;
messageListener();
} }
private void applicationClose() { private void applicationClose() {
connectionHandler.setState(DISCONNECTED); disconnect();
} }
@FXML @FXML
private void toggleConnection () { private void toggleConnection () {
if (connectionHandler == null || connectionHandler.getStateObjectProperty().get() != CONNECTED) { if (connectionHandler == null || connectionHandler.getStateProperty().get() != CONNECTED) {
connect(); connect();
} else { } else {
disconnect(); disconnect();
@@ -71,19 +66,19 @@ public class ChatWindowController {
startConnectionHandler(); startConnectionHandler();
connectionHandler.connect(); connectionHandler.connect();
} catch(ChatProtocolException | IOException e) { } catch(ChatProtocolException | IOException e) {
messages.addMessage(null,null, e.getMessage(), Message.MessageType.ERROR); addError(e.getMessage());
} }
} }
private void disconnect() { private void disconnect() {
if (connectionHandler == null) { if (connectionHandler == null) {
messages.addMessage(null,null,"No connection handler", Message.MessageType.ERROR); addError("No connection handler");
return; return;
} }
try { try {
connectionHandler.disconnect(); connectionHandler.disconnect();
} catch (ChatProtocolException e) { } catch (ChatProtocolException e) {
messages.addMessage(null,null, e.getMessage(), Message.MessageType.ERROR); addError(e.getMessage());
} }
} }
@@ -92,32 +87,33 @@ public class ChatWindowController {
String messageString = messageField.getText().strip(); String messageString = messageField.getText().strip();
try { try {
if (connectionHandler == null) { if (connectionHandler == null) {
messages.addMessage(null,null,"No connection handler", Message.MessageType.ERROR); addError("No connection handler");
} else if (!connectionHandler.message(messageString)) { } else if (!connectionHandler.message(messageString)) {
messages.addMessage(null,null,"Not a valid message format.", Message.MessageType.ERROR); addError("Not a valid message format.");
} else { } else {
messageField.clear(); messageField.clear();
} }
} catch (ChatProtocolException e) { } catch (ChatProtocolException e) {
messages.addMessage(null,null, e.getMessage(), Message.MessageType.ERROR); addError(e.getMessage());
} }
} }
//TODO: TEST
@FXML @FXML
private void applyFilter( ) { private void applyFilter( ) {
messages.getFilteredMessages(filterValue.getText().strip()); this.redrawMessageList();
} }
private void startConnectionHandler() throws IOException { private void startConnectionHandler() throws IOException {
String userName = userNameField.getText(); String userName = userNameField.getText();
String serverAddress = serverAddressField.getText(); String serverAddress = serverAddressField.getText();
int serverPort = Integer.parseInt(serverPortField.getText()); int serverPort = Integer.parseInt(serverPortField.getText());
connectionHandler = new ClientConnectionHandler(messages,serverAddress,serverPort,userName); connectionHandler = new ClientConnectionHandler(
NetworkHandler.openConnection(serverAddress, serverPort), userName,
messages);
new Thread(connectionHandler).start(); new Thread(connectionHandler).start();
//register changelistener //register Listener
startChangeListener(); startListener();
// register window close handler // register window close handler
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler); rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
@@ -132,7 +128,7 @@ public class ChatWindowController {
} }
} }
public void stateChanged(State newState) { public void stateChanged(ConnectionHandler.State newState) {
// update UI (need to be run in UI thread: see Platform.runLater()) // update UI (need to be run in UI thread: see Platform.runLater())
Platform.runLater(new Runnable() { Platform.runLater(new Runnable() {
@Override @Override
@@ -145,49 +141,6 @@ public class ChatWindowController {
} }
} }
private void startChangeListener() {
//Listener for State
connectionHandler.getStateObjectProperty().addListener(new ChangeListener<State>() {
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
stateChanged(newValue);
}
});
//Listener for Username
connectionHandler.getUserNameProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
setUserName(newValue);
}
});
//Listener for Address
connectionHandler.getServerAddressProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
setServerAddress(newValue);
}
});
//Listener for Port
connectionHandler.getServerPortProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
setServerPort(newValue.intValue());
}
});
}
public void setMessageField(String message) {
Platform.runLater(new Runnable() {
@Override
public void run() {
messageField.setText(message);
}
});
}
public void setUserName(String userName) { public void setUserName(String userName) {
Platform.runLater(new Runnable() { Platform.runLater(new Runnable() {
@Override @Override
@@ -215,7 +168,10 @@ public class ChatWindowController {
}); });
} }
//TODO: MAKE ChangeListener public void addError(String message) {
messages.addMessage(new Message(Message.MessageType.ERROR, null, null, message));
}
private void redrawMessageList() { private void redrawMessageList() {
this.messageArea.clear(); this.messageArea.clear();
Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip()))); Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
@@ -228,4 +184,43 @@ public class ChatWindowController {
} }
public void startListener() {
connectionHandler.getStateProperty().addListener(new ChangeListener<State>() {
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
stateChanged(newValue);
}
});
connectionHandler.getUserNameProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
setUserName(newValue);
}
});
connectionHandler.getServerAddressProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
setServerAddress(newValue);
}
});
connectionHandler.getServerPortProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
setServerPort(newValue.intValue());
}
});
}
private void messageListener() {
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
redrawMessageList();
}
});
}
} }
@@ -1,8 +1,8 @@
package ch.zhaw.pm2.multichat.client; package ch.zhaw.pm2.multichat.client;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException; import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler; import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.SimpleStringProperty;
@@ -13,73 +13,54 @@ import java.net.SocketException;
import java.util.Scanner; import java.util.Scanner;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*; public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
import static ch.zhaw.pm2.multichat.client.Message.MessageType.*;
public class ClientConnectionHandler implements Runnable {
private NetworkHandler.NetworkConnection<String> connection;
// 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 SimpleStringProperty userName;
private SimpleIntegerProperty serverPort;
private SimpleStringProperty serverAddress;
private ObjectProperty<State> stateObjectProperty;
private ClientMessageList messageList;
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" ); private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
enum State { private SimpleStringProperty userName;
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED; private SimpleObjectProperty<State> state;
} private ClientMessageList messages;
private SimpleStringProperty serverAddress;
private SimpleIntegerProperty serverPort;
public ClientConnectionHandler(ClientMessageList messageList,String serverAddress,int serverPort,String userName) throws IOException { public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
this.stateObjectProperty = new SimpleObjectProperty<>(NEW); String userName,
ClientMessageList messages) {
super(connection);
this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName); this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName);
this.serverPort = new SimpleIntegerProperty(); this.messages = messages;
this.serverAddress = new SimpleStringProperty(); state = new SimpleObjectProperty<>(State.NEW);
this.messageList = messageList; serverAddress = new SimpleStringProperty();
this.connection = NetworkHandler.openConnection(serverAddress,serverPort); serverPort = new SimpleIntegerProperty();
} }
public ObjectProperty<State> getStateObjectProperty() { public SimpleStringProperty getServerAddressProperty() { return serverAddress; }
return stateObjectProperty;
public SimpleIntegerProperty getServerPortProperty() { return serverPort; }
public SimpleObjectProperty<State> getStateProperty() {
return this.state;
} }
public SimpleStringProperty getUserNameProperty() { public SimpleStringProperty getUserNameProperty() { return userName; }
return userName;
}
public SimpleStringProperty getServerAddressProperty() {
return serverAddress;
}
public SimpleIntegerProperty getServerPortProperty() {
return serverPort;
}
public void setState (State newState) { public void setState (State newState) {
this.stateObjectProperty.set(newState); state.set(newState);
} }
public void run () { public void run () {
startReceiving(); startReceiving();
} }
public void startReceiving() { private void startReceiving() {
System.out.println("Starting Connection Handler"); System.out.println("Starting Connection Handler");
try { try {
System.out.println("Start receiving data..."); System.out.println("Start receiving data...");
while (connection.isAvailable()) { while (getConnection().isAvailable()) {
String data = connection.receive(); String data = getConnection().receive();
processData(data); processData(data);
} }
System.out.println("Stopped recieving data"); System.out.println("Stopped recieving data");
@@ -103,7 +84,7 @@ public class ClientConnectionHandler implements Runnable {
System.out.println("Closing Connection Handler to Server"); System.out.println("Closing Connection Handler to Server");
try { try {
System.out.println("Stop receiving data..."); System.out.println("Stop receiving data...");
connection.close(); getConnection().close();
System.out.println("Stopped receiving data."); System.out.println("Stopped receiving data.");
} catch (IOException e) { } catch (IOException e) {
System.err.println("Failed to close connection." + e.getMessage()); System.err.println("Failed to close connection." + e.getMessage());
@@ -111,7 +92,6 @@ public class ClientConnectionHandler implements Runnable {
System.out.println("Closed Connection Handler to Server"); System.out.println("Closed Connection Handler to Server");
} }
private void processData(String data) { private void processData(String data) {
try { try {
// parse data content // parse data content
@@ -139,52 +119,52 @@ public class ClientConnectionHandler implements Runnable {
payload = scanner.nextLine(); payload = scanner.nextLine();
} }
// dispatch operation based on type parameter // dispatch operation based on type parameter
if (type.equals(DATA_TYPE_CONNECT)) { if (type.equals(getDataTypeConnect())) {
System.err.println("Illegal connect request from server"); System.err.println("Illegal connect request from server");
} else if (type.equals(DATA_TYPE_CONFIRM)) { } else if (type.equals(getDataTypeConfirm())) {
if (stateObjectProperty.get() == CONFIRM_CONNECT) { if (state.get() == CONFIRM_CONNECT) {
this.userName.set(reciever); this.userName.set(reciever);
this.serverAddress.set(connection.getRemoteHost()); this.serverPort.set(getConnection().getRemotePort());
this.serverPort.set(connection.getRemotePort()); this.serverAddress.set(getConnection().getRemoteHost());
messageList.addMessage(sender,reciever,payload,INFO); messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
System.out.println("CONFIRM: " + payload); System.out.println("CONFIRM: " + payload);
this.setState(CONNECTED); this.setState(CONNECTED);
} else if (stateObjectProperty.get() == CONFIRM_DISCONNECT) { } else if (state.get() == CONFIRM_DISCONNECT) {
messageList.addMessage(sender,reciever,payload,INFO); messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
System.out.println("CONFIRM: " + payload); System.out.println("CONFIRM: " + payload);
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
} else { } else {
System.err.println("Got unexpected confirm message: " + payload); System.err.println("Got unexpected confirm message: " + payload);
} }
} else if (type.equals(DATA_TYPE_DISCONNECT)) { } else if (type.equals(getDataTypeDisconnect())) {
if (stateObjectProperty.get() == DISCONNECTED) { if (state.get() == DISCONNECTED) {
System.out.println("DISCONNECT: Already in disconnected: " + payload); System.out.println("DISCONNECT: Already in disconnected: " + payload);
return; return;
} }
messageList.addMessage(sender,reciever,payload,INFO); messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
System.out.println("DISCONNECT: " + payload); System.out.println("DISCONNECT: " + payload);
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
} else if (type.equals(DATA_TYPE_MESSAGE)) { } else if (type.equals(getDataTypeMessage())) {
if (stateObjectProperty.get() != CONNECTED) { if (state.get() != CONNECTED) {
System.out.println("MESSAGE: Illegal state " + stateObjectProperty.get() + " for message: " + payload); System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
return; return;
} }
messageList.addMessage(sender,reciever,payload,MESSAGE); messages.addMessage(new Message(Message.MessageType.MESSAGE,sender,reciever,payload));
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload); System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
} else if (type.equals(DATA_TYPE_ERROR)) { } else if (type.equals(getDataTypeError())) {
messageList.addMessage(sender,reciever,payload,ERROR); messages.addMessage(new Message(Message.MessageType.ERROR,sender,reciever,payload));
System.out.println("ERROR: " + payload); System.out.println("ERROR: " + payload);
} else { } else {
System.out.println("Unknown data type received: " + type); System.out.println("Unknown data type received: " + type);
} }
} catch (ChatProtocolException e) { } catch (ChatProtocolException e) {
System.err.println("Error while processing data: " + e.getMessage()); System.err.println("Error while processing data: " + e.getMessage());
sendData(USER_NONE, userName.get(), DATA_TYPE_ERROR, e.getMessage()); sendData(USER_NONE, userName.get(), getDataTypeError(), e.getMessage());
} }
} }
public void sendData(String sender, String receiver, String type, String payload) { private void sendData(String sender, String receiver, String type, String payload) {
if (connection.isAvailable()) { if (getConnection().isAvailable()) {
new StringBuilder(); new StringBuilder();
String data = new StringBuilder() String data = new StringBuilder()
.append(sender+"\n") .append(sender+"\n")
@@ -193,7 +173,7 @@ public class ClientConnectionHandler implements Runnable {
.append(payload+"\n") .append(payload+"\n")
.toString(); .toString();
try { try {
connection.send(data); getConnection().send(data);
} catch (SocketException e) { } catch (SocketException e) {
System.err.println("Connection closed: " + e.getMessage()); System.err.println("Connection closed: " + e.getMessage());
} catch (EOFException e) { } catch (EOFException e) {
@@ -205,19 +185,19 @@ public class ClientConnectionHandler implements Runnable {
} }
public void connect() throws ChatProtocolException { public void connect() throws ChatProtocolException {
if (stateObjectProperty.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + stateObjectProperty.get()); if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
this.sendData(userName.get(), USER_NONE, DATA_TYPE_CONNECT,null); this.sendData(userName.get(), USER_NONE, getDataTypeConnect(),null);
this.setState(CONFIRM_CONNECT); this.setState(CONFIRM_CONNECT);
} }
public void disconnect() throws ChatProtocolException { public void disconnect() throws ChatProtocolException {
if (stateObjectProperty.get() != NEW && stateObjectProperty.get() != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + stateObjectProperty.get()); if (state.get() != NEW && state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + state);
this.sendData(userName.get(), USER_NONE, DATA_TYPE_DISCONNECT,null); this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(),null);
this.setState(CONFIRM_DISCONNECT); this.setState(CONFIRM_DISCONNECT);
} }
public boolean message(String messageString) throws ChatProtocolException { public boolean message(String messageString) throws ChatProtocolException {
if (stateObjectProperty.get() != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + stateObjectProperty.get()); if (state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state);
Matcher matcher = messagePattern.matcher(messageString); Matcher matcher = messagePattern.matcher(messageString);
if (matcher.find()) { if (matcher.find()) {
@@ -227,7 +207,7 @@ public class ClientConnectionHandler implements Runnable {
return false; return false;
} }
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL; if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
this.sendData(userName.get(), receiver, DATA_TYPE_MESSAGE,message); this.sendData(userName.get(), receiver, getDataTypeMessage(),message);
return true; return true;
} else { } else {
return false; return false;
@@ -1,33 +1,16 @@
package ch.zhaw.pm2.multichat.client; package ch.zhaw.pm2.multichat.client;
import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.USER_NONE;
public class ClientMessageList { public class ClientMessageList {
private List<Message> messages; private List<Message> messages = new ArrayList<>();
private SimpleBooleanProperty changed; private SimpleBooleanProperty changed = new SimpleBooleanProperty(false);
public ClientMessageList() { public void addMessage(Message message) {
messages = new ArrayList<>(); messages.add(message);
changed = new SimpleBooleanProperty(true);
}
public SimpleBooleanProperty getChangedProperty() {
return changed;
}
public void addMessage(String sender, String receiver, String message, Message.MessageType type) {
if(sender == null) {
sender = USER_NONE;
}
messages.add(new Message(type, sender, receiver, message));
changed.set(!changed.get()); changed.set(!changed.get());
} }
@@ -48,21 +31,11 @@ public class ClientMessageList {
return result.toString(); return result.toString();
} }
public String getMessages() { public void clear() {
StringBuilder result = new StringBuilder(); messages = new ArrayList<>();
for(Message message : messages) { changed.set(!changed.get());
switch (message.getType()) {
case MESSAGE -> result.append(String.format("[%s -> %s] %s\n", message.getSender(), message.getReceiver(), message.getText()));
case ERROR -> result.append(String.format("[ERROR] %s\n", message.getText()));
case INFO -> result.append(String.format("[INFO] %s\n", message.getText()));
default -> result.append(String.format("[ERROR] %s\n", "Unexpected message type: " + message.getType()));
}
}
return result.toString();
} }
public void clear() { public SimpleBooleanProperty getChangedProperty() { return changed; }
messages = new SimpleListProperty<>();
}
} }
@@ -17,9 +17,11 @@ public class ClientUI extends Application {
private void chatWindow(Stage primaryStage) { private void chatWindow(Stage primaryStage) {
try { try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("ChatWindow.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("ChatWindow.fxml"));
Pane rootPane = loader.load(); Pane rootPane = loader.load();
ChatWindowController chatWindowController = loader.getController();
chatWindowController.setMessages(clientMessageList);
// fill in scene and stage setup // fill in scene and stage setup
Scene scene = new Scene(rootPane); Scene scene = new Scene(rootPane);
//scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); //scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
@@ -0,0 +1,51 @@
package ch.zhaw.pm2.multichat.protocol;
public abstract class ConnectionHandler {
private NetworkHandler.NetworkConnection<String> connection;
// 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 = "*";
public enum State {
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
}
public ConnectionHandler(NetworkHandler.NetworkConnection<String> connection) {
this.connection = connection;
}
public static String getDataTypeConnect() {
return DATA_TYPE_CONNECT;
}
public static String getDataTypeConfirm() {
return DATA_TYPE_CONFIRM;
}
public static String getDataTypeDisconnect() {
return DATA_TYPE_DISCONNECT;
}
public static String getDataTypeMessage() {
return DATA_TYPE_MESSAGE;
}
public static String getDataTypeError() {
return DATA_TYPE_ERROR;
}
public NetworkHandler.NetworkConnection<String> getConnection() {
return connection;
}
protected void setConnection() {
this.connection = connection;
}
}
@@ -6,6 +6,8 @@ import java.io.IOException;
import java.net.SocketException; import java.net.SocketException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Server { public class Server {
@@ -62,23 +64,34 @@ public class Server {
} }
private void start() { private void start() {
ReentrantLock mutex = new ReentrantLock();
Condition nameComplete = mutex.newCondition();
System.out.println("Server started."); System.out.println("Server started.");
try { try {
while (true) { while (true) {
NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection(); NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection();
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections); ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections, mutex, nameComplete);
new Thread(connectionHandler).start(); new Thread(connectionHandler).start();
mutex.lock();
try {
nameComplete.await();
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>", System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
connectionHandler.getUserName(), connectionHandler.getUserName(),
connection.getRemoteHost(), connection.getRemoteHost(),
connection.getRemotePort() connection.getRemotePort()
)); ));
} }
finally {
mutex.unlock();
}
}
} catch(SocketException e) { } catch(SocketException e) {
System.out.println("Server connection terminated"); System.out.println("Server connection terminated");
} }
catch (IOException e) { catch (IOException e) {
System.err.println("Communication error " + e); System.err.println("Communication error " + e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} }
// close server // close server
System.out.println("Server Stopped."); System.out.println("Server Stopped.");
@@ -1,6 +1,7 @@
package ch.zhaw.pm2.multichat.server; package ch.zhaw.pm2.multichat.server;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException; import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler; import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import java.io.EOFException; import java.io.EOFException;
@@ -11,24 +12,19 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Scanner; import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*; import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
public class ServerConnectionHandler implements Runnable{ public class ServerConnectionHandler extends ConnectionHandler implements Runnable{
private static final AtomicInteger connectionCounter = new AtomicInteger(0); private static final AtomicInteger connectionCounter = new AtomicInteger(0);
private final int connectionId = connectionCounter.incrementAndGet(); private final int connectionId = connectionCounter.incrementAndGet();
private final NetworkHandler.NetworkConnection<String> connection;
private final Map<String,ServerConnectionHandler> connectionRegistry; private final Map<String,ServerConnectionHandler> connectionRegistry;
// Data types used for the Chat Protocol private ReentrantLock mutex;
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 Condition nameComplete;
private static final String USER_ALL = "*";
private String userName = "Anonymous-"+connectionId; private String userName = "Anonymous-"+connectionId;
private State state = NEW; private State state = NEW;
@@ -43,23 +39,25 @@ public class ServerConnectionHandler implements Runnable{
} }
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection, public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
Map<String,ServerConnectionHandler> registry) { Map<String,ServerConnectionHandler> registry, ReentrantLock mutex, Condition nameComplete) {
super(connection);
Objects.requireNonNull(connection, "Connection must not be null"); Objects.requireNonNull(connection, "Connection must not be null");
Objects.requireNonNull(registry, "Registry must not be null"); Objects.requireNonNull(registry, "Registry must not be null");
this.connection = connection;
this.connectionRegistry = registry; this.connectionRegistry = registry;
this.mutex = mutex;
this.nameComplete = nameComplete;
} }
public String getUserName() { public String getUserName() {
return this.userName; return this.userName;
} }
public void startReceiving() { private void startReceiving() {
System.out.println("Starting Connection Handler for " + userName); System.out.println("Starting Connection Handler for new User");
try { try {
System.out.println("Start receiving data..."); System.out.println("Start receiving data...");
while (connection.isAvailable()) { while (getConnection().isAvailable()) {
String data = connection.receive(); String data = getConnection().receive();
processData(data); processData(data);
} }
System.out.println("Stopped recieving data"); System.out.println("Stopped recieving data");
@@ -71,19 +69,20 @@ public class ServerConnectionHandler implements Runnable{
System.out.println("Connection terminated by remote"); System.out.println("Connection terminated by remote");
connectionRegistry.remove(userName); connectionRegistry.remove(userName);
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage()); System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
} catch(IOException e) { } catch (IOException e) {
System.err.println("Communication error: " + e); System.err.println("Communication error: " + e);
} catch(ClassNotFoundException e) { } catch (ClassNotFoundException e) {
System.err.println("Received object of unknown type: " + e.getMessage()); System.err.println("Received object of unknown type: " + e.getMessage());
} }
System.out.println("Stopping Connection Handler for " + userName); System.out.println("Stopping Connection Handler for " + userName);
} }
public void stopReceiving() { private void stopReceiving() {
System.out.println("Closing Connection Handler for " + userName); System.out.println("Closing Connection Handler for " + userName);
try { try {
System.out.println("Stop receiving data..."); System.out.println("Stop receiving data...");
connection.close(); getConnection().close();
System.out.println("Stopped receiving data."); System.out.println("Stopped receiving data.");
} catch (IOException e) { } catch (IOException e) {
System.err.println("Failed to close connection." + e); System.err.println("Failed to close connection." + e);
@@ -119,27 +118,34 @@ public class ServerConnectionHandler implements Runnable{
} }
// dispatch operation based on type parameter // dispatch operation based on type parameter
if (type.equals(DATA_TYPE_CONNECT)) { if (type.equals(getDataTypeConnect())) {
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state); if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
if (sender == null || sender.isBlank()) sender = this.userName; if (sender == null || sender.isBlank()) sender = this.userName;
if (connectionRegistry.containsKey(sender)) if (connectionRegistry.containsKey(sender))
throw new ChatProtocolException("User name already taken: " + sender); throw new ChatProtocolException("User name already taken: " + sender);
mutex.lock();
try {
this.userName = sender; this.userName = sender;
nameComplete.signal();
}
finally {
mutex.unlock();
}
connectionRegistry.put(userName, this); connectionRegistry.put(userName, this);
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Registration successfull for " + userName); sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
this.state = CONNECTED; this.state = CONNECTED;
} else if (type.equals(DATA_TYPE_CONFIRM)) { } else if (type.equals(getDataTypeConfirm())) {
System.out.println("Not expecting to receive a CONFIRM request from client"); System.out.println("Not expecting to receive a CONFIRM request from client");
} else if (type.equals(DATA_TYPE_DISCONNECT)) { } else if (type.equals(getDataTypeDisconnect())) {
if (state == DISCONNECTED) if (state == DISCONNECTED)
throw new ChatProtocolException("Illegal state for disconnect request: " + state); throw new ChatProtocolException("Illegal state for disconnect request: " + state);
if (state == CONNECTED) { if (state == CONNECTED) {
connectionRegistry.remove(this.userName); connectionRegistry.remove(this.userName);
} }
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Confirm disconnect of " + userName); sendData(USER_NONE, userName, getDataTypeConfirm(), "Confirm disconnect of " + userName);
this.state = DISCONNECTED; this.state = DISCONNECTED;
this.stopReceiving(); this.stopReceiving();
} else if (type.equals(DATA_TYPE_MESSAGE)) { } else if (type.equals(getDataTypeMessage())) {
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state); if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state);
if (USER_ALL.equals(reciever)) { if (USER_ALL.equals(reciever)) {
for (ServerConnectionHandler handler : connectionRegistry.values()) { for (ServerConnectionHandler handler : connectionRegistry.values()) {
@@ -149,11 +155,14 @@ public class ServerConnectionHandler implements Runnable{
ServerConnectionHandler handler = connectionRegistry.get(reciever); ServerConnectionHandler handler = connectionRegistry.get(reciever);
if (handler != null) { if (handler != null) {
handler.sendData(sender, reciever, type, payload); handler.sendData(sender, reciever, type, payload);
if(!reciever.equals(sender)){
sendData(sender, reciever, type, payload); //send message to sender if it's a direct message and sender is not receiver.
}
} else { } else {
this.sendData(USER_NONE, userName, DATA_TYPE_ERROR, "Unknown User: " + reciever); this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + reciever);
} }
} }
} else if (type.equals(DATA_TYPE_ERROR)) { } else if (type.equals(getDataTypeError())) {
System.err.println("Received error from client (" + sender + "): " + payload); System.err.println("Received error from client (" + sender + "): " + payload);
} else { } else {
System.err.println("Unknown data type received: " + type); System.err.println("Unknown data type received: " + type);
@@ -161,12 +170,12 @@ public class ServerConnectionHandler implements Runnable{
} }
} catch(ChatProtocolException e) { } catch(ChatProtocolException e) {
System.out.println("Error while processing data" + e.getMessage()); System.out.println("Error while processing data" + e.getMessage());
sendData(USER_NONE, userName, DATA_TYPE_ERROR, e.getMessage()); sendData(USER_NONE, userName, getDataTypeError(), e.getMessage());
} }
} }
public void sendData(String sender, String receiver, String type, String payload) { private void sendData(String sender, String receiver, String type, String payload) {
if (connection.isAvailable()) { if (getConnection().isAvailable()) {
new StringBuilder(); new StringBuilder();
String data = new StringBuilder() String data = new StringBuilder()
.append(sender+"\n") .append(sender+"\n")
@@ -175,7 +184,7 @@ public class ServerConnectionHandler implements Runnable{
.append(payload+"\n") .append(payload+"\n")
.toString(); .toString();
try { try {
connection.send(data); getConnection().send(data);
} catch (SocketException e) { } catch (SocketException e) {
System.out.println("Connection closed: " + e.getMessage()); System.out.println("Connection closed: " + e.getMessage());
} catch (EOFException e) { } catch (EOFException e) {