Compare commits

...
Author SHA1 Message Date
Andrin Fassbind 40e3e14666 fixed #49
clean up
2022-04-16 22:09:56 +02:00
Andrin Fassbind a189fedd76 fixed #49
clean up
2022-04-16 22:01:59 +02:00
Andrin Fassbind 6498b8ab33 fixed #49 2022-04-16 21:12:55 +02:00
Andrin Fassbind 77e9cf6163 Attempt to send obj 2022-04-16 21:04:51 +02:00
Roman SchenkandGitHub Enterprise b67b9c84aa Merge pull request #47 from PM2-IT21bWIN-ruiz-mach-krea/Java_Doc_and_Formatting
Java doc and formatting
2022-04-16 20:06:03 +02:00
Roman SchenkandGitHub Enterprise a678635355 Merge branch 'main' into Java_Doc_and_Formatting 2022-04-16 20:05:45 +02:00
schrom01 ff916daa51 Merge remote-tracking branch 'origin/Java_Doc_and_Formatting' into Java_Doc_and_Formatting 2022-04-16 20:02:16 +02:00
schrom01 61feb48a86 fixed Problem in processData in ConnectionHandler.java
and Codecleanup
2022-04-16 20:02:04 +02:00
Andrin Fassbind b4b91ea513 klassendiagramm 2022-04-16 19:53:15 +02:00
Andrin Fassbind dad15d52d2 javadoc 2022-04-16 19:40:51 +02:00
Andrin Fassbind 8395a121bb Klassendiagramm 2022-04-16 19:21:30 +02:00
Leonardo Brandenberger 8cb83ef7ef Fixed whitespaces ChatWindow.fxml other javadocs in other classes aswell deleted unneccessary declarations 2022-04-16 16:58:37 +02:00
Leonardo Brandenberger 154b9d435d Further improved Java Docs 10 missing todos. 2022-04-16 16:23:25 +02:00
Leonardo Brandenberger 048dc36a7c Merge branch 'main' into Java_Doc_and_Formatting
# Conflicts:
#	client/src/main/java/ch/zhaw/pm2/multichat/client/ChatWindowController.java
#	client/src/main/java/ch/zhaw/pm2/multichat/client/ClientConnectionHandler.java
#	protocol/src/main/java/ch/zhaw/pm2/multichat/protocol/ConnectionHandler.java
#	server/src/main/java/ch/zhaw/pm2/multichat/server/Server.java
#	server/src/main/java/ch/zhaw/pm2/multichat/server/ServerConnectionHandler.java
2022-04-16 15:59:21 +02:00
Leonardo Brandenberger c732e82260 General Codestyle and higlighted todos 2022-04-16 08:19:44 +02:00
Leonardo Brandenberger 2acfa708e9 ClientUI JavaDocs finished 2022-04-16 07:10:03 +02:00
Leonardo Brandenberger 7c8bdb3b33 improved java doc in ChatWindowController and Client class finished Client Connection Handler in Progress 2022-04-16 06:36:08 +02:00
Leonardo Brandenberger 4edcc92649 improved java doc in ChatWindowController and Client class finished 2022-04-16 06:36:08 +02:00
Leonardo Brandenberger dcee52cc1b Started Java Doc in ChatWindowController 2022-04-16 06:36:07 +02:00
Leonardo Brandenberger 6d6b9f1564 Java Doc and CodeStyle improvements 2022-04-16 06:36:05 +02:00
Andrin FassbindandLeonardo Brandenberger c9aed1affd javadoc 2022-04-16 06:36:05 +02:00
schrom01andLeonardo Brandenberger 1d9beb6b7d fixed Problem setting Username in ClientConnectionHandler
#42
2022-04-16 06:36:05 +02:00
Andrin FassbindandLeonardo Brandenberger add410250f fixed issue #39 2022-04-16 06:36:05 +02:00
Andrin FassbindandLeonardo Brandenberger 5c0e55870d Java Doc Server && ServerConnectionHandler 2022-04-16 06:36:05 +02:00
Andrin FassbindandLeonardo Brandenberger a94a4c81d8 Shrink code in the ConnectionHandlers 2022-04-16 06:36:05 +02:00
Andrin FassbindandLeonardo Brandenberger 5022974427 Shrink code in the ConnectionHandlers 2022-04-16 06:36:04 +02:00
schrom01andLeonardo Brandenberger 46b0e4386a sovled #42 2022-04-16 06:36:02 +02:00
Andrin Fassbind a5069e938f javadoc 2022-04-15 22:06:22 +02:00
fassbandandGitHub Enterprise 119cd1eb52 Merge pull request #46 from PM2-IT21bWIN-ruiz-mach-krea/refactoring_chatwindowcontroller
fixed Problem setting Username in ClientConnectionHandler
2022-04-15 21:40:36 +02:00
schrom01 e53a751081 fixed Problem setting Username in ClientConnectionHandler
#42
2022-04-15 21:20:03 +02:00
Roman SchenkandGitHub Enterprise 64a6137372 Merge pull request #45 from PM2-IT21bWIN-ruiz-mach-krea/remove_server_lock
fixed issue #39
2022-04-15 21:18:13 +02:00
Andrin Fassbind 5257195d82 fixed issue #39 2022-04-15 21:13:28 +02:00
Andrin Fassbind 73dcfb5058 Java Doc Server && ServerConnectionHandler 2022-04-15 19:41:43 +02:00
Roman SchenkandGitHub Enterprise 84e59effec Merge pull request #44 from PM2-IT21bWIN-ruiz-mach-krea/continue_connectionhandler
Continue connectionhandler
2022-04-15 17:41:12 +02:00
Leonardo Brandenberger 5f6266c017 Java Doc and CodeStyle improvements 2022-04-15 17:10:24 +02:00
schrom01andLeonardo Brandenberger 77b3057911 removed Method initialize because it's not used anymore. 2022-04-15 17:10:24 +02:00
schrom01andLeonardo Brandenberger 9e027b5c7a sovled #42 2022-04-15 17:10:23 +02:00
Andrin Fassbind 9a534b2465 Shrink code in the ConnectionHandlers 2022-04-15 16:39:52 +02:00
Andrin Fassbind 37045ade15 Shrink code in the ConnectionHandlers 2022-04-15 16:25:45 +02:00
Leonardo BrandenbergerandGitHub Enterprise 313a4f5861 Merge pull request #43 from PM2-IT21bWIN-ruiz-mach-krea/refactoring_chatwindowcontroller
Refactoring chatwindowcontroller to improve MVC
2022-04-15 15:39:47 +02:00
schrom01 2b70299507 removed Method initialize because it's not used anymore. 2022-04-15 15:35:04 +02:00
schrom01 2b01e92e8d sovled #42 2022-04-15 15:34:03 +02:00
Leonardo Brandenberger 28376f1242 trying to fix MVC 2022-04-15 04:57:46 +02:00
Roman SchenkandGitHub Enterprise a75d3466ef Merge pull request #41 from PM2-IT21bWIN-ruiz-mach-krea/Server_Console_Display
Fixes issue #37
2022-04-15 01:07:22 +02:00
Leonardo Brandenberger 97b6fff82e fixes #37 2022-04-15 00:14:22 +02:00
fassbandandGitHub Enterprise 2a8b701f48 Merge pull request #40 from PM2-IT21bWIN-ruiz-mach-krea/Refactoring_ClientConnectionHandler
Refactoring client connection handler
2022-04-14 22:24:13 +02:00
schrom01 86aa801b34 removed Enum State from ServerConnectionHandler.java because it's in ConnectionHandler.java now. 2022-04-14 22:23:49 +02:00
schrom01 2277fee73a merging 2022-04-14 22:12:35 +02:00
schrom01 d8dbd93c15 Merge branch 'main' into Refactoring_ClientConnectionHandler
# Conflicts:
#	client/src/main/java/ch/zhaw/pm2/multichat/client/ChatWindowController.java
#	client/src/main/java/ch/zhaw/pm2/multichat/client/ClientConnectionHandler.java
2022-04-14 22:02:39 +02:00
Roman SchenkandGitHub Enterprise 6e8e560d73 Merge pull request #38 from PM2-IT21bWIN-ruiz-mach-krea/ConnectionHandlerClass
Connection handler class
2022-04-14 21:51:59 +02:00
Andrin Fassbind 5a26c6b127 create setConnection in ConnectionHandlerClass 2022-04-14 21:37:06 +02:00
schrom01 615b3844e3 refactoring of ClientConnectionHandler
Instance is now created in ClientUI.java
solved #24 and #15
2022-04-14 21:13:36 +02:00
Andrin Fassbind 5e6e9d5817 Create ConnectionHandlerClass
Remove Codeduplication
2022-04-14 21:11:58 +02:00
Roman SchenkandGitHub Enterprise 4a998b0f61 Merge pull request #36 from PM2-IT21bWIN-ruiz-mach-krea/SpecialCharacterUsername
Special character username
2022-04-14 20:39:05 +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
Andrin Fassbind b6fd5b569d fixed Issue #28 by checking if username contains space before starting connection 2022-04-14 19:33:18 +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
Andrin Fassbind b47d98b960 fixed Issue #19 by changing messagePattern 2022-04-14 12:11:03 +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
fassbandandGitHub Enterprise 9eb352c0fe Merge pull request #25 from PM2-IT21bWIN-ruiz-mach-krea/Class_Message
Class Message
2022-04-12 15:23:35 +02:00
fassbandandGitHub Enterprise a27b7f4446 Merge pull request #27 from PM2-IT21bWIN-ruiz-mach-krea/ChatWindow_Layout
Chat window layout
2022-04-12 15:23:22 +02:00
schrom01 1a188f6bbd Fixed Problem "Empty Messages can be sent" if receiver != * 2022-04-12 14:26:26 +02:00
schrom01 56200b749d added Javadoc in Class Message 2022-04-12 12:36:43 +02:00
schrom01 7e7333dfaf fixed matchesFilter in Message.java
Problem solved if any String is null.
2022-04-12 11:01:28 +02:00
schrom01 3082da8a91 Solved Problem "Empty Messages can be sent" 2022-04-12 10:00:31 +02:00
schrom01 424a174847 refactoring Methods message() in ChatWindowController and ClientConnectionHandler 2022-04-12 09:43:24 +02:00
schrom01 b246c3c7e3 fix Problem with StringBuilder in ClientMessageList 2022-04-12 08:59:53 +02:00
schrom01 eb0e6d0dbc Refactoring creating ClientMessageList Object in ClientUI 2022-04-12 08:43:19 +02:00
schrom01 0896257fad Refactoring ClientMessageList 2022-04-12 08:25:21 +02:00
schrom01 e11fb136cf created Class Message 2022-04-12 07:36:14 +02:00
12 changed files with 940 additions and 484 deletions
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 133 KiB

@@ -1,9 +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;
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.NetworkHandler; import ch.zhaw.pm2.multichat.protocol.Message;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
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;
@@ -13,122 +16,162 @@ 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.*;
/**
* Class Representing the Controller Element of the Window, also Contains the Elements that contacts the View Elements via
* Listeners and Observable Objects.
* To Contact the Model Elements needed it also holds references to message and the Connectionhandler.
*/
public class ChatWindowController { public class ChatWindowController {
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
private ClientConnectionHandler connectionHandler; private ClientConnectionHandler connectionHandler;
private ClientMessageList messages; private ClientMessageList messages;
private final WindowCloseHandler windowCloseHandler = new WindowCloseHandler(); 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 @FXML
public void initialize() { private Pane rootPane;
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName()); @FXML
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT)); private TextField serverAddressField;
stateChanged(NEW); @FXML
messages = new ClientMessageList(this); private TextField serverPortField;
@FXML
private TextField userNameField;
@FXML
private TextField messageField;
@FXML
private TextArea messageArea;
@FXML
private Button connectButton;
@FXML
private TextField filterValue;
@FXML
private Button sendButton;
/**
* Takes a message object and stores it used as Model and also starts message Listener via messageListener method.
*
* @param messages Object that will be set for use as Model
*/
public void setMessages(ClientMessageList messages) {
this.messages = messages;
messageListener();
} }
/**
* Takes a Connection handler object and stores it used as Model and also starts a Listener for it.
*
* @param connectionHandler that will be set and used as Model.
*/
public void setConnectionHandler(ClientConnectionHandler connectionHandler) {
this.connectionHandler = connectionHandler;
startConnectionHandlerListener();
serverAddressField.setText(connectionHandler.getServerAddressProperty().get());
serverPortField.setText(String.valueOf(connectionHandler.getServerPortProperty().get()));
}
/**
* Method which closes the Application via use of the disconnect Method.
*/
private void applicationClose() { private void applicationClose() {
connectionHandler.setState(DISCONNECTED); disconnect();
} }
/**
* Method that handles the Connect Button and Initiates connect when connectionHandler is not Connected or
* a disconnect when it is connected.
*/
@FXML @FXML
private void toggleConnection () { private void toggleConnection() {
if (connectionHandler == null || connectionHandler.getState() != CONNECTED) { if (connectionHandler == null || connectionHandler.getStateProperty().get() != CONNECTED) {
connect(); connect();
} else { } else {
disconnect(); disconnect();
} }
} }
/**
* Initiates a connection by starting Connection Handler and telling, the Handler to start a connection.
*/
private void connect() { private void connect() {
try { try {
messages = new ClientMessageList(this); // clear message list messages.clear(); // clear message list
startConnectionHandler(); startConnectionHandler();
connectionHandler.connect(); connectionHandler.connect();
} catch(ChatProtocolException | IOException e) { } catch (ChatProtocolException | IOException e) {
writeError(e.getMessage()); addError("Error while starting Connection Handler and connect" + e);
} }
} }
/**
* Initiates disconnecting of the connectionHandler, also checks if connectionHandler is available.
*/
private void disconnect() { private void disconnect() {
if (connectionHandler == null) { if (connectionHandler == null) {
writeError("No connection handler"); addError("No connection handler");
return; return;
} }
try { try {
connectionHandler.disconnect(); connectionHandler.disconnect();
} catch (ChatProtocolException e) { } catch (ChatProtocolException e) {
writeError(e.getMessage()); addError(e.getMessage());
} }
} }
/**
* Method which is used when the send button is pressed and handing over a message to the Connection Handler
*/
@FXML @FXML
private void message() { private void message() {
if (connectionHandler == null) {
writeError("No connection handler");
return;
}
String messageString = messageField.getText().strip(); String messageString = messageField.getText().strip();
messageField.clear();
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 { try {
connectionHandler.message(receiver, message); if (connectionHandler == null) {
} catch (ChatProtocolException e) { addError("No connection handler");
writeError(e.getMessage()); } else if (!connectionHandler.message(messageString)) {
} addError("Not a valid message format.");
} else { } else {
writeError("Not a valid message format."); messageField.clear();
}
} catch (ChatProtocolException e) {
addError(e.getMessage());
} }
} }
/**
* Method which is used when a Filter is applied
* Setting the Text in the message area after sending it through the filter.
*/
@FXML @FXML
private void applyFilter( ) { private void applyFilter() {
this.redrawMessageList(); Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
} }
/**
* Starts the ConnectionHandler setting the username and Checking if the name follows the valid format of no spaces.
*
* @throws IOException for error that may occur during initialization of connectionHandler.
*/
private void startConnectionHandler() throws IOException { private void startConnectionHandler() throws IOException {
String userName = userNameField.getText(); String userName = userNameField.getText();
if (!userName.contains(" ")) {
String serverAddress = serverAddressField.getText(); String serverAddress = serverAddressField.getText();
int serverPort = Integer.parseInt(serverPortField.getText()); int serverPort = Integer.parseInt(serverPortField.getText());
connectionHandler = new ClientConnectionHandler( connectionHandler.initialize(serverAddress, serverPort, userName);
NetworkHandler.openConnection(serverAddress, serverPort), userName,
this);
new Thread(connectionHandler).start(); new Thread(connectionHandler).start();
// register window close handler
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler); rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
} } else {
addError("It is not allowed to have spaces in username!");
private void terminateConnectionHandler() {
// unregister window close handler
rootPane.getScene().getWindow().removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
if (connectionHandler != null) {
connectionHandler.stopReceiving();
connectionHandler = null;
} }
} }
/**
* Sets the state shown according to the state the method receives, if state indicates disconnected it will also inform the
* Connection Handler and tell it to stop Receiving more messages.
*
* @param newState is the state that it should be set to.
*/
public void stateChanged(State newState) { public void stateChanged(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() {
@@ -138,10 +181,15 @@ public class ChatWindowController {
} }
}); });
if (newState == DISCONNECTED) { if (newState == DISCONNECTED) {
terminateConnectionHandler(); connectionHandler.stopReceiving();
} }
} }
/**
* Sets displayed username according to the String provided.
*
* @param userName provided String that is set as name.
*/
public void setUserName(String userName) { public void setUserName(String userName) {
Platform.runLater(new Runnable() { Platform.runLater(new Runnable() {
@Override @Override
@@ -151,6 +199,11 @@ public class ChatWindowController {
}); });
} }
/**
* Sets displayed Server Address.
*
* @param serverAddress provided String that is set as server address.
*/
public void setServerAddress(String serverAddress) { public void setServerAddress(String serverAddress) {
Platform.runLater(new Runnable() { Platform.runLater(new Runnable() {
@Override @Override
@@ -160,6 +213,11 @@ public class ChatWindowController {
}); });
} }
/**
* Sets displayed Server port.
*
* @param serverPort provided String that is set as server port.
*/
public void setServerPort(int serverPort) { public void setServerPort(int serverPort) {
Platform.runLater(new Runnable() { Platform.runLater(new Runnable() {
@Override @Override
@@ -169,51 +227,71 @@ public class ChatWindowController {
}); });
} }
public void addMessage(String sender, String receiver, String message) { /**
messages.addMessage(ClientMessageList.MessageType.MESSAGE, sender, receiver, message); * Method which adds an incoming String as an Error Message.
this.redrawMessageList(); *
} * @param message String to be added as Error
*/
public void addInfo(String message) {
messages.addMessage(ClientMessageList.MessageType.INFO, null, null, message);
this.redrawMessageList();
}
public void addError(String message) { public void addError(String message) {
messages.addMessage(ClientMessageList.MessageType.ERROR, null, null, message); messages.addMessage(new Message(ConnectionHandler.DATA_TYPE.DATA_TYPE_ERROR, null, null, message));
this.redrawMessageList();
} }
public void clearMessageArea() { /**
this.messageArea.clear(); * Nested Class in charge of Closing the window
} */
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> { class WindowCloseHandler implements EventHandler<WindowEvent> {
/**
* @param event the event which occurred when Windows is closed
*/
public void handle(WindowEvent event) { public void handle(WindowEvent event) {
applicationClose(); applicationClose();
} }
} }
/**
* Starts several new Listener for Connection Handler changes by using several observable properties.
*/
public void startConnectionHandlerListener() {
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());
}
});
}
/**
* Starts a new Listener for messages by using the observable Boolean.
*/
private void messageListener() {
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
Platform.runLater(() -> messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
}
});
}
} }
@@ -2,8 +2,16 @@ package ch.zhaw.pm2.multichat.client;
import javafx.application.Application; import javafx.application.Application;
/**
* Client Main Class in charge of starting the UI only contains main method.
*/
public class Client { public class Client {
/**
* Main method which launches the Client UI
*
* @param args no arguments needed
*/
public static void main(String[] args) { public static void main(String[] args) {
// Start UI // Start UI
System.out.println("Starting Client Application"); System.out.println("Starting Client Application");
@@ -1,66 +1,132 @@
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.Message;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler; import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import java.io.EOFException; import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import java.net.SocketException; import java.net.SocketException;
import java.util.Scanner; import java.util.Scanner;
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 ClientConnectionHandler implements Runnable { /**
private final NetworkHandler.NetworkConnection<String> connection; * Client Connection Handler Class is used for the connection of the Client to a server
private final ChatWindowController controller; * it is used part as a Model storing properties like userName, state, serverAddress and Port.
* Also holds methods to
*/
public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
// Data types used for the Chat Protocol private final Pattern messagePattern = Pattern.compile("^(?:@(\\S*))?\\s*(.*)$");
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 = ""; private final SimpleStringProperty userName;
public static final String USER_ALL = "*"; private final SimpleObjectProperty<State> state;
private final ClientMessageList messages;
private final SimpleStringProperty serverAddress;
private final SimpleIntegerProperty serverPort;
private String userName = USER_NONE; /**
private State state = NEW; * Constructor initializes ConnectionHandler by Setting default values for the fields and stores the given messages itself.
*
enum State { * @param messages
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED; */
public ClientConnectionHandler(ClientMessageList messages) {
super();
this.messages = messages;
state = new SimpleObjectProperty<>(State.NEW);
serverAddress = new SimpleStringProperty(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
serverPort = new SimpleIntegerProperty(NetworkHandler.DEFAULT_PORT);
this.userName = new SimpleStringProperty(null);
} }
public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection, /**
String userName, * Called to initialize the ClientConnectionHandler when trying to start a connection
ChatWindowController controller) { *
this.connection = connection; * @param serverAddress to connect to
this.userName = (userName == null || userName.isBlank())? USER_NONE : userName; * @param serverPort to connect to
this.controller = controller; * @param userName to connect as
* @throws IOException if connection to Server not possible
*/
public void initialize(String serverAddress, int serverPort, String userName) throws IOException {
state.set(NEW);
this.serverAddress.set(serverAddress);
this.serverPort.set(serverPort);
setConnection(NetworkHandler.openConnection(serverAddress, serverPort));
this.userName.set((userName == null || userName.isBlank()) ? USER_NONE : userName);
} }
public State getState() { /**
* Observable getter Method for the stored serverAddress
*
* @return the stored serverAddress
*/
public SimpleStringProperty getServerAddressProperty() {
return serverAddress;
}
/**
* Observable getter Method for the stored serverPort
*
* @return the stored serverPort
*/
public SimpleIntegerProperty getServerPortProperty() {
return serverPort;
}
/**
* Observable getter Method for the stored state
*
* @return the stored state
*/
public SimpleObjectProperty<State> getStateProperty() {
return this.state; return this.state;
} }
public void setState (State newState) { /**
this.state = newState; * Observable getter Method for the stored userName
controller.stateChanged(newState); *
* @return the stored userName
*/
public SimpleStringProperty getUserNameProperty() {
return userName;
} }
public void run () { /**
* Method which sets a new State.
*
* @param newState the state that will be set
*/
public void setState(State newState) {
state.set(newState);
}
/**
* Standard run method which will directly start the startReceiving method.
*/
public void run() {
startReceiving(); startReceiving();
} }
public void startReceiving() { /**
* Method that is started by the run method, starts a connection handler.
* Figures out if connection is available if not determines the error cause and gives an error accordingly.
*/
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(); Message data = getConnection().receive();
processData(data); processData(data);
} }
System.out.println("Stopped recieving data"); System.out.println("Stopped receiving data");
} catch (SocketException e) { } catch (SocketException e) {
System.out.println("Connection terminated locally"); System.out.println("Connection terminated locally");
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
@@ -69,19 +135,22 @@ public class ClientConnectionHandler implements Runnable {
System.out.println("Connection terminated by remote"); System.out.println("Connection terminated by remote");
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
System.err.println("Unregistered because connection terminated" + e.getMessage()); System.err.println("Unregistered because connection terminated" + 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("Stopped Connection Handler"); System.out.println("Stopped Connection Handler");
} }
/**
* Method which is used to stop receiving data, gets the current connection and closes it.
*/
public void stopReceiving() { public void stopReceiving() {
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());
@@ -89,114 +158,129 @@ 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) { /**
try { * Method which processes data and determines its type then uses the corresponding method to process it.
// parse data content *
Scanner scanner = new Scanner(data); * @param data that is received in a form of a String and then used depending on its determined cause.
String sender = null; */
String reciever = null; private void processData(Message data) {
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 // dispatch operation based on type parameter
if (type.equals(DATA_TYPE_CONNECT)) { if (data.getType() == DATA_TYPE.DATA_TYPE_CONNECT) {
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 (data.getType() == DATA_TYPE.DATA_TYPE_CONFIRM) {
if (state == CONFIRM_CONNECT) { caseConfirm(data);
this.userName = reciever; } else if (data.getType() == DATA_TYPE.DATA_TYPE_DISCONNECT) {
controller.setUserName(userName); caseDisconnect(data);
controller.setServerPort(connection.getRemotePort()); } else if (data.getType() == DATA_TYPE.DATA_TYPE_MESSAGE) {
controller.setServerAddress(connection.getRemoteHost()); caseMessage(data);
controller.addInfo(payload); } else if (data.getType() == DATA_TYPE.DATA_TYPE_ERROR) {
System.out.println("CONFIRM: " + payload); caseError(data);
} else {
System.out.println("Unknown data type received: " + data.getType());
}
}
private void caseConfirm(Message data) {
if (state.get() == CONFIRM_CONNECT) {
this.userName.set(data.getReceiver());
this.serverPort.set(getConnection().getRemotePort());
this.serverAddress.set(getConnection().getRemoteHost());
messages.addMessage(data);
System.out.println("CONFIRM: " + data.getText());
this.setState(CONNECTED); this.setState(CONNECTED);
} else if (state == CONFIRM_DISCONNECT) { } else if (state.get() == CONFIRM_DISCONNECT) {
controller.addInfo(payload); messages.addMessage(data);
System.out.println("CONFIRM: " + payload); System.out.println("CONFIRM: " + data.getText());
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
} else { } else {
System.err.println("Got unexpected confirm message: " + payload); System.err.println("Got unexpected confirm message: " + data.getText());
}
} 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()) { * Initiates the disconnect sequence and sends the message with all its info.
new StringBuilder(); *
String data = new StringBuilder() * @param data Data which has been transmitted
.append(sender+"\n") */
.append(receiver+"\n") private void caseDisconnect(Message data) {
.append(type+"\n") if (state.get() == DISCONNECTED) {
.append(payload+"\n") System.out.println("DISCONNECT: Already in disconnected: " + data.getText());
.toString(); return;
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());
}
} }
messages.addMessage(data);
System.out.println("DISCONNECT: " + data.getText());
this.setState(DISCONNECTED);
} }
/**
* Initiates the procedure to send a new message and sends one as such.
*
* @param data Data which has been transmitted
*/
private void caseMessage(Message data) {
if (state.get() != CONNECTED) {
System.out.println("MESSAGE: Illegal state " + state + " for message: " + data.getText());
return;
}
messages.addMessage(data);
System.out.println("MESSAGE: From " + data.getSender() + " to " + data.getReceiver() + ": " + data.getText());
}
/**
* Stores the message as an error message and displays it as such as well.
*
* @param data Data which has been transmitted
*/
private void caseError(Message data) {
messages.addMessage(data);
System.out.println("ERROR: " + data.getText());
}
/**
* Send connect attempt to Server
*
* @throws ChatProtocolException Error that is thrown if the state is not set to NEW
*/
public void connect() throws ChatProtocolException { public void connect() throws ChatProtocolException {
if (state != NEW) throw new ChatProtocolException("Illegal state for connect: " + state); if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
this.sendData(userName, USER_NONE, DATA_TYPE_CONNECT,null); this.sendData(userName.get(), USER_NONE, getDataTypeConnect(), null);
this.setState(CONFIRM_CONNECT); this.setState(CONFIRM_CONNECT);
} }
/**
* Send Disconnect attempt to server
*
* @throws ChatProtocolException Error tha si thrown if state is invalid
*/
public void disconnect() throws ChatProtocolException { public void disconnect() throws ChatProtocolException {
if (state != NEW && state != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + state); if (state.get() != NEW && state.get() != CONNECTED)
this.sendData(userName, USER_NONE, DATA_TYPE_DISCONNECT,null); throw new ChatProtocolException("Illegal state for disconnect: " + state);
this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(), null);
this.setState(CONFIRM_DISCONNECT); this.setState(CONFIRM_DISCONNECT);
} }
public void message(String receiver, String message) throws ChatProtocolException { /**
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state); * Sends message to Server
this.sendData(userName, receiver, DATA_TYPE_MESSAGE,message); *
} * @param messageString The message the user wants to send
* @return true if message is valid else false
* @throws ChatProtocolException if illegal connection state
*/
public boolean message(String messageString) throws ChatProtocolException {
if (state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state);
Matcher matcher = messagePattern.matcher(messageString);
if (matcher.find()) {
String receiver = matcher.group(1);
String message = matcher.group(2);
if (message.length() < 1) {
return false;
}
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
this.sendData(userName.get(), receiver, getDataTypeMessage(), message);
return true;
} else {
return false;
}
}
} }
@@ -1,51 +1,68 @@
package ch.zhaw.pm2.multichat.client; package ch.zhaw.pm2.multichat.client;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import ch.zhaw.pm2.multichat.protocol.Message;
import javafx.beans.property.SimpleBooleanProperty;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
/**
* Class that is used to store the messages in an ArrayList
* And also as a Model that informs the controller via Listeners that can be initialized
*/
public class ClientMessageList { public class ClientMessageList {
private final List<MessageType> typeList = new ArrayList<>(); private List<Message> messages = new ArrayList<>();
private final List<String> senderList = new ArrayList<>(); private final SimpleBooleanProperty changed = new SimpleBooleanProperty(false);
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; * Adds a new message to ArrayList and also informs Listener.
*
* @param message that should be added
*/
public void addMessage(Message message) {
messages.add(message);
changed.set(!changed.get());
} }
public void addMessage(MessageType type, String sender, String receiver, String message) { /**
typeList.add(type); * Applies a given filter over all messages and returns the result as a new String.
senderList.add(sender); * Method is also in charge of applying the correct prefix to the message according to its type.
receiverList.add(receiver); *
messageList.add(message); * @param filter is the applied filter on all the messages that are stored.
} * @return String that matches the given filter.
*/
public void writeFilteredMessages(String filter) { public String getFilteredMessages(String filter) {
StringBuilder result = new StringBuilder();
boolean showAll = filter == null || filter.isBlank(); boolean showAll = filter == null || filter.isBlank();
gui.clearMessageArea(); for (Message message : messages) {
for(int i=0; i<senderList.size(); i++) { if (showAll || message.matchesFilter(filter)) {
String sender = Objects.requireNonNullElse(senderList.get(i),""); switch (message.getType()) {
String receiver = Objects.requireNonNullElse(receiverList.get(i),""); case DATA_TYPE_MESSAGE -> result.append(String.format("[%s -> %s] %s\n", message.getSender(), message.getReceiver(), message.getText()));
String message = Objects.requireNonNull(messageList.get(i), ""); case DATA_TYPE_ERROR -> result.append(String.format("[ERROR] %s\n", message.getText()));
if(showAll || case DATA_TYPE_CONFIRM, DATA_TYPE_DISCONNECT, DATA_TYPE_CONNECT -> result.append(String.format("[INFO] %s\n", message.getText()));
sender.contains(filter) || default -> result.append(String.format("[ERROR] %s\n", "Unexpected message type: " + message.getType()));
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));
} }
} }
} }
return result.toString();
} }
public enum MessageType { /**
INFO, MESSAGE, ERROR; * Overwrites the Arraylist of messages, clearing it, also informs all Listeners.
*/
public void clear() {
messages = new ArrayList<>();
changed.set(!changed.get());
}
/**
* Getter Method to check the current value of SimpleBooleanProperty changed.
*
* @return the current value of changed
*/
public SimpleBooleanProperty getChangedProperty() {
return changed;
} }
} }
@@ -6,17 +6,41 @@ import javafx.scene.Scene;
import javafx.scene.layout.Pane; import javafx.scene.layout.Pane;
import javafx.stage.Stage; import javafx.stage.Stage;
/**
* Class in charge of initializing and loading elements needed for the GUI.
* Also Launching the chat window with pre-given parameters
*/
public class ClientUI extends Application { public class ClientUI extends Application {
private final ClientMessageList clientMessageList = new ClientMessageList();
private final ClientConnectionHandler connectionHandler = new ClientConnectionHandler(clientMessageList);
/**
* Start method will only run the chatWindow method.
*
* @param primaryStage the primary stage for this application, onto which
* the application scene can be set.
* Applications may create other stages, if needed, but they will not be
* primary stages.
*/
@Override @Override
public void start(Stage primaryStage) { public void start(Stage primaryStage) {
chatWindow(primaryStage); chatWindow(primaryStage);
} }
/**
* Method is in charge of loading the FXML file and then initializing the controllers and setting some parameters for the stage.
*
* @param primaryStage of the Application onto which the Scene is set.
*/
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);
chatWindowController.setConnectionHandler(connectionHandler);
// 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());
@@ -27,7 +51,7 @@ public class ClientUI extends Application {
primaryStage.setTitle("Multichat Client"); primaryStage.setTitle("Multichat Client");
primaryStage.show(); primaryStage.show();
primaryStage.setMinWidth(primaryStage.getWidth()); //use automatically computed size as Minimum Size. primaryStage.setMinWidth(primaryStage.getWidth()); //use automatically computed size as Minimum Size.
} catch(Exception e) { } catch (Exception e) {
System.err.println("Error starting up UI" + e.getMessage()); System.err.println("Error starting up UI" + e.getMessage());
} }
} }
@@ -12,7 +12,9 @@
<?import javafx.scene.layout.HBox?> <?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?> <?import javafx.scene.layout.VBox?>
<BorderPane fx:id="rootPane" minWidth="-Infinity" prefHeight="500.0" prefWidth="420.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ch.zhaw.pm2.multichat.client.ChatWindowController"> <BorderPane xmlns:fx="http://javafx.com/fxml/1" fx:id="rootPane" minWidth="-Infinity" prefHeight="500.0"
prefWidth="420.0" xmlns="http://javafx.com/javafx/18"
fx:controller="ch.zhaw.pm2.multichat.client.ChatWindowController">
<top> <top>
<VBox BorderPane.alignment="CENTER"> <VBox BorderPane.alignment="CENTER">
<children> <children>
@@ -22,7 +24,7 @@
<items> <items>
<MenuItem mnemonicParsing="false" text="press Enter"> <MenuItem mnemonicParsing="false" text="press Enter">
<graphic> <graphic>
<TextField fx:id="filterValue" onAction="#applyFilter" /> <TextField fx:id="filterValue" onAction="#applyFilter"/>
</graphic> </graphic>
</MenuItem> </MenuItem>
</items> </items>
@@ -31,30 +33,35 @@
</MenuBar> </MenuBar>
<HBox fillHeight="false" spacing="5.0"> <HBox fillHeight="false" spacing="5.0">
<children> <children>
<TextField fx:id="userNameField" alignment="CENTER_RIGHT" maxWidth="1.7976931348623157E308" minWidth="110.0" promptText="Username" HBox.hgrow="SOMETIMES" /> <TextField fx:id="userNameField" alignment="CENTER_RIGHT" maxWidth="1.7976931348623157E308"
<Label alignment="CENTER" contentDisplay="CENTER" text="\@" textAlignment="CENTER" textOverrun="CLIP" HBox.hgrow="NEVER"> minWidth="110.0" promptText="Username" HBox.hgrow="SOMETIMES"/>
<Label alignment="CENTER" contentDisplay="CENTER" text="\@" textAlignment="CENTER"
textOverrun="CLIP" HBox.hgrow="NEVER">
<HBox.margin> <HBox.margin>
<Insets bottom="5.0" top="5.0" /> <Insets bottom="5.0" top="5.0"/>
</HBox.margin> </HBox.margin>
</Label> </Label>
<TextField fx:id="serverAddressField" alignment="CENTER_RIGHT" minWidth="110.0" promptText="Host" HBox.hgrow="SOMETIMES" /> <TextField fx:id="serverAddressField" alignment="CENTER_RIGHT" minWidth="110.0"
promptText="Host" HBox.hgrow="SOMETIMES"/>
<Label text=":" HBox.hgrow="NEVER"> <Label text=":" HBox.hgrow="NEVER">
<HBox.margin> <HBox.margin>
<Insets bottom="5.0" top="5.0" /> <Insets bottom="5.0" top="5.0"/>
</HBox.margin> </HBox.margin>
</Label> </Label>
<TextField fx:id="serverPortField" minWidth="-Infinity" prefWidth="60.0" promptText="Port" HBox.hgrow="NEVER" /> <TextField fx:id="serverPortField" minWidth="-Infinity" prefWidth="60.0" promptText="Port"
<Button fx:id="connectButton" maxWidth="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#toggleConnection" prefWidth="80.0" text="Connect" HBox.hgrow="NEVER"> 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> <HBox.margin>
<Insets left="5.0" /> <Insets left="5.0"/>
</HBox.margin> </HBox.margin>
</Button> </Button>
</children> </children>
<BorderPane.margin> <BorderPane.margin>
<Insets /> <Insets/>
</BorderPane.margin> </BorderPane.margin>
<padding> <padding>
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0" /> <Insets bottom="5.0" left="5.0" right="5.0" top="5.0"/>
</padding> </padding>
</HBox> </HBox>
</children> </children>
@@ -63,22 +70,23 @@
<bottom> <bottom>
<HBox spacing="5.0"> <HBox spacing="5.0">
<children> <children>
<TextField fx:id="messageField" onAction="#message" HBox.hgrow="ALWAYS" /> <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"> <Button fx:id="sendButton" alignment="CENTER" maxWidth="-Infinity" minWidth="-Infinity"
mnemonicParsing="false" onAction="#message" prefWidth="50.0" text="Send" textAlignment="CENTER">
<HBox.margin> <HBox.margin>
<Insets left="5.0" /> <Insets left="5.0"/>
</HBox.margin> </HBox.margin>
</Button> </Button>
</children> </children>
<padding> <padding>
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0" /> <Insets bottom="5.0" left="5.0" right="5.0" top="5.0"/>
</padding> </padding>
</HBox> </HBox>
</bottom> </bottom>
<center> <center>
<TextArea fx:id="messageArea" editable="false" wrapText="true"> <TextArea fx:id="messageArea" editable="false" wrapText="true">
<BorderPane.margin> <BorderPane.margin>
<Insets left="5.0" right="5.0" /> <Insets left="5.0" right="5.0"/>
</BorderPane.margin> </BorderPane.margin>
</TextArea> </TextArea>
</center> </center>
@@ -0,0 +1,101 @@
package ch.zhaw.pm2.multichat.protocol;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketException;
/**
* This abstract class is the superclass for ClientConnectionHandler and ServerConnectionHandler
* It offers the DATA_TYPE for message and a {@link State} enum for all valid connection states.
* Shared methods are implemented in this class as well {@link ConnectionHandler#sendData(String, String, DATA_TYPE, String)}
*/
public abstract class ConnectionHandler {
private NetworkHandler.NetworkConnection<String> connection;
public static final String USER_NONE = "";
public static final String USER_ALL = "*";
// State of the connection
public enum State {
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED, ERROR;
}
// DATA_TYPE of the messages
public enum DATA_TYPE {
DATA_TYPE_CONNECT, DATA_TYPE_CONFIRM, DATA_TYPE_DISCONNECT, DATA_TYPE_MESSAGE, DATA_TYPE_ERROR
}
/**
* @return {@link DATA_TYPE}
*/
public static DATA_TYPE getDataTypeConnect() {
return DATA_TYPE.DATA_TYPE_CONNECT;
}
/**
* @return {@link DATA_TYPE}
*/
public static DATA_TYPE getDataTypeConfirm() {
return DATA_TYPE.DATA_TYPE_CONFIRM;
}
/**
* @return {@link DATA_TYPE}
*/
public static DATA_TYPE getDataTypeDisconnect() {
return DATA_TYPE.DATA_TYPE_DISCONNECT;
}
/**
* @return {@link DATA_TYPE}
*/
public static DATA_TYPE getDataTypeMessage() {
return DATA_TYPE.DATA_TYPE_MESSAGE;
}
/**
* @return {@link DATA_TYPE}
*/
public static DATA_TYPE getDataTypeError() {
return DATA_TYPE.DATA_TYPE_ERROR;
}
/**
* @return {@link NetworkHandler.NetworkConnection}
*/
public NetworkHandler.NetworkConnection<String> getConnection() {
return connection;
}
/**
* This method sets the NetworkConnection used for the server <-> client connection
*
* @param connection NetworkConnection used for the server <-> client connection
*/
protected void setConnection(NetworkHandler.NetworkConnection<String> connection) {
this.connection = connection;
}
/**
* This method gets called to send data via the socket defined in the {@link NetworkHandler.NetworkConnection}
*
* @param sender of the data
* @param receiver of the data
* @param type of the data
* @param payload of the data
*/
protected void sendData(String sender, String receiver, DATA_TYPE type, String payload) {
if (connection.isAvailable()) {
try {
connection.send(new Message(type, sender, receiver, payload));
} 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());
}
}
}
}
@@ -0,0 +1,69 @@
package ch.zhaw.pm2.multichat.protocol;
import java.io.Serializable;
/**
* A Message object represents one Message of a client. Can be stored in ClientMessageList.
*/
public class Message implements Serializable {
private final ConnectionHandler.DATA_TYPE type;
private final String sender;
private final String receiver;
private final String text;
/**
* Constructor of Message. Needs all Information about a Message to save them.
*
* @param type Message (if it's a message typed by a user), Error or Information (if it is generated automatically, in this case sender and receiver will be null)
* @param sender The User who has sent the message.
* @param receiver The User who should receive the message.
* @param text The Text of the message.
*/
public Message(ConnectionHandler.DATA_TYPE type, String sender, String receiver, String text) {
this.type = type;
this.sender = sender;
this.receiver = receiver;
this.text = text;
}
/**
* Checks if the Filter String is contained in one of the data fields sender, receiver or text
*
* @param filter The Filter String
* @return true if it is the Filter String is contained in a data field.
*/
public boolean matchesFilter(String filter) {
return (sender != null && sender.contains(filter)) ||
(receiver != null && receiver.contains(filter)) ||
(text != null && text.contains(filter));
}
/**
* @return The type of the message.
*/
public ConnectionHandler.DATA_TYPE getType() {
return type;
}
/**
* @return The User who has sent the Message.
*/
public String getSender() {
return sender;
}
/**
* @return The Receiver who receives the Message.
*/
public String getReceiver() {
return receiver;
}
/**
* @return The Text of the Message.
*/
public String getText() {
return text;
}
}
@@ -38,7 +38,7 @@ import java.util.Objects;
* on the client side, usually the result is displayed to the user). After processing is finished the * 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. * process calls {@link NetworkConnection#receive()} again to wait for the next request.
* </li> * </li>
* <li>sending data: call {@link NetworkConnection#send(Serializable data)}, which sends the given data * <li>sending data: call {@link NetworkConnection#send(Message)}, which sends the given data
* object to the remote side. The method returns as soon the object has been transmitted. * 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 * <b>Important: {@link NetworkConnection} is not thread safe</b>, therefore make sure that only one thread
* at a time is sending data.</li> * at a time is sending data.</li>
@@ -270,7 +270,7 @@ public class NetworkHandler {
* on the client side, usually the result is displayed to the user). After processing is finished the * 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. * process calls {@link NetworkConnection#receive()} again to wait for the next request.
* </li> * </li>
* <li>sending data: call {@link NetworkConnection#send(Serializable data)}, which sends the given data * <li>sending data: call {@link NetworkConnection#send(Message)}, which sends the given data
* object to the remote side. The method returns as soon the object has been transmitted. * 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 * <b>Important: {@link NetworkConnection} is not thread safe</b>, therefore make sure that only one thread
* at a time is sending data. * at a time is sending data.
@@ -305,7 +305,7 @@ public class NetworkHandler {
* @param data data object of type T to be submitted through the connection. * @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, ...) * @throws IOException if an error occurs (e.g. connection interrupted while sending, ...)
*/ */
public synchronized void send(T data) throws IOException { public synchronized void send(Message data) throws IOException {
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream()); ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.writeObject(data); outputStream.writeObject(data);
} }
@@ -320,9 +320,9 @@ public class NetworkHandler {
* @throws IOException if an error occours. (e.g. terminated locally/remotely) see above. * @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 * @throws ClassNotFoundException if the data object received does not match any class in the local classpath
*/ */
public T receive() throws IOException, ClassNotFoundException { public Message receive() throws IOException, ClassNotFoundException {
ObjectInputStream inputStream = new ObjectInputStream(this.socket.getInputStream()); ObjectInputStream inputStream = new ObjectInputStream(this.socket.getInputStream());
return (T) inputStream.readObject(); return (Message) inputStream.readObject();
} }
/** /**
@@ -8,14 +8,38 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/**
* This Class represents a Server. The user can start the programm with the port number as a argument.
* If no argument has been set the {@link NetworkHandler#DEFAULT_PORT} is used as port number.
* After initialising the server:
* 1. Starts a Socketserver using the logic given in {@link NetworkHandler.NetworkServer#createServer()}
* 2. The server starts to listen for incoming connection using the Logic given in {@link NetworkHandler.NetworkServer#waitForConnection()}
* 3. New connections will be attached to a Connection handler: {@link ServerConnectionHandler} and placed in a Map containing all active connections {@link Server#connections}
*/
public class Server { public class Server {
// Server connection // Server connection
private NetworkHandler.NetworkServer<String> networkServer; private final NetworkHandler.NetworkServer<String> networkServer;
// Connection registry // Connection registry
private Map<String,ServerConnectionHandler> connections = new HashMap<>(); private final Map<String, ServerConnectionHandler> connections = new HashMap<>();
/**
* The Constructor to create a new instance.
*
* @param serverPort to listen for incoming connections.
* @throws IOException thrown if an I/O error occurs when opening the socket.
*/
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());
}
/**
* @param args
*/
public static void main(String[] args) { public static void main(String[] args) {
// Parse arguments for server port. // Parse arguments for server port.
try { try {
@@ -54,36 +78,30 @@ public class Server {
} }
} }
public Server(int serverPort) throws IOException { /**
// Open server connection * With this methode the instance waits for incoming connections. If a client tries to connect to the server.
System.out.println("Create server connection"); * The connection will be registered in the connection registry if successful.
networkServer = NetworkHandler.createServer(serverPort); */
System.out.println("Listening on " + networkServer.getHostAddress() + ":" + networkServer.getHostPort());
}
private void start() { private void start() {
System.out.println("Server started."); System.out.println("Server started.");
try { try {
while (true) { while (networkServer.isAvailable()) {
NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection(); NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection();
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections); ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections);
new Thread(connectionHandler).start(); new Thread(connectionHandler).start();
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
connectionHandler.getUserName(),
connection.getRemoteHost(),
connection.getRemotePort()
));
} }
} 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);
} }
// close server // close server
System.out.println("Server Stopped."); System.out.println("Server Stopped.");
} }
/**
* This method will stop the serversocket.
*/
public void terminate() { public void terminate() {
try { try {
System.out.println("Close server port."); System.out.println("Close server port.");
@@ -1,68 +1,92 @@
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 static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
import ch.zhaw.pm2.multichat.protocol.Message;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler; import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import java.io.EOFException; import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import java.net.SocketException; import java.net.SocketException;
import java.util.HashMap;
import java.util.Map; 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.ReentrantLock;
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
public class ServerConnectionHandler implements Runnable{ /**
* This class represents the connection between the server and a client and offers the serverside logic.
* The ServerConnectionHandler receives data send from the client as well as sends data to the client.
* <p>
* The ServeConnectionHandler offers following functionality:
* <p>
* Evaluating connection attempts from a client by:
* 1. Checks if Username is valid (Not used)
* 2. Saves Username in {@link ServerConnectionHandler#userName}
* 3. Saves the connection in the {@link ServerConnectionHandler#connectionRegistry}
* <p>
* Processes disconnections from a client by:
* 1. Removing the connection from the {@link ServerConnectionHandler#connectionRegistry}
* 2. Terminates the socket by calling {@link NetworkHandler.NetworkConnection#close()}
* <p>
* Process Messages send from a client by:
* 1. Evaluating the receiver by differentiating between broadcast or unicast.
* 2. Sending the message accordingly.
* <p>
* To use this class, start a new instance and start it in a thread.
* To constructor needs following parameter:
* 1. {@link ch.zhaw.pm2.multichat.protocol.NetworkHandler.NetworkConnection} representing the socket connection between server and client
* 2. {@link Map<String,ServerConnectionHandler>} registry to check for all active connections
* 3. {@link ReentrantLock @link Condition} to lock server thread to evaluate connection.
*/
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 String userName = "Anonymous-" + connectionId;
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; private State state = NEW;
/**
* Called when runnable gets started in a thread.
*/
@Override @Override
public void run() { public void run() {
startReceiving(); startReceiving();
} }
enum State { /**
NEW, CONNECTED, DISCONNECTED; * Constructor to initialize the connection
} *
* @param connection representing the socket connection between server and client
* @param registry map containing all active connections between server and clients
*/
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection, public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
Map<String,ServerConnectionHandler> registry) { Map<String, ServerConnectionHandler> registry) {
super();
setConnection(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;
} }
public String getUserName() { /**
return this.userName; * These methods runs in a while-loop as long as the socket between server and client is available
} * and the connection State is not ERROR.
*/
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() && !(state == ERROR)) {
String data = connection.receive(); Message data = getConnection().receive();
processData(data); processData(data);
} }
System.out.println("Stopped recieving data"); System.out.println("Stopped receiving data");
} catch (SocketException e) { } catch (SocketException e) {
System.out.println("Connection terminated locally"); System.out.println("Connection terminated locally");
connectionRegistry.remove(userName); connectionRegistry.remove(userName);
@@ -71,117 +95,138 @@ 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());
} }
if (state == ERROR) {
System.out.println("Stopping Connection Handler for Rejected Client");
} else {
System.out.println("Stopping Connection Handler for " + userName); System.out.println("Stopping Connection Handler for " + userName);
} }
public void stopReceiving() { }
/**
* This method will call {@link NetworkHandler.NetworkConnection#close()} to close the Socket.
*/
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.getMessage());
} }
System.out.println("Closed Connection Handler for " + userName); System.out.println("Closed Connection Handler for " + userName);
} }
private void processData(String data) { /**
* This method gets called when socket receives data. The method checks for the data type and reacts accordingly
* If data type:
* 1. Connect => checks if username is valid. if valid sends response to client with confirmation.
* If username not valid quits connection by changing status to ERROR.
* 2. Confirm => Server should not receive this kind of message. STDOUT informs about it.
* 3. Disconnect => Disconnects connection by removing connection from registry and calling method to terminate socket.
* 4. Message => Checks if broadcast or unicast. Sends data accordingly
* 5. Error => STDERR message
*
* @param data received by the server
*/
private void processData(Message data) {
try { try {
// parse data content // dispatch operation based on type parameter
Scanner scanner = new Scanner(data); if (data.getType() == DATA_TYPE.DATA_TYPE_CONNECT) {
String sender = null; caseConnect(data);
String reciever = null; } else if (data.getType() == DATA_TYPE.DATA_TYPE_CONFIRM) {
String type = null; System.out.println("Not expecting to receive a CONFIRM request from client");
String payload = null; } else if (data.getType() == DATA_TYPE.DATA_TYPE_DISCONNECT) {
if (scanner.hasNextLine()) { caseDisconnect();
sender = scanner.nextLine(); } else if (data.getType() == DATA_TYPE.DATA_TYPE_MESSAGE) {
caseMessage(data);
} else if (data.getType() == DATA_TYPE.DATA_TYPE_ERROR) {
System.err.println("Received error from client (" + data.getSender() + "): " + data.getText());
} else { } else {
throw new ChatProtocolException("No Sender found"); System.err.println("Unknown data type received: " + data.getType());
} }
if (scanner.hasNextLine()) { } catch (ChatProtocolException e) {
reciever = scanner.nextLine(); System.out.println("Error while processing data " + e.getMessage());
} else { sendData(USER_NONE, userName, getDataTypeError(), e.getMessage());
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)) { * This method is called by method {@link ServerConnectionHandler#processData(Message)}
* Checks if username is valid. if valid sends response to client with confirmation.
*
* @param data sent
* @throws ChatProtocolException if username not valid
*/
private void caseConnect(Message data) throws ChatProtocolException {
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 username not valid
if (connectionRegistry.containsKey(sender)) if (connectionRegistry.containsKey(data.getSender())) {
throw new ChatProtocolException("User name already taken: " + sender); state = ERROR;
this.userName = sender; System.out.println(String.format("Connecting failed for new Client with IP:Port <%s:%d>.\nReason: Name already taken.",
getConnection().getRemoteHost(),
getConnection().getRemotePort()));
throw new ChatProtocolException("User name already taken: " + data.getSender());
}
//if username valid
if (!data.getSender().isBlank()) {
this.userName = data.getSender();
}
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 successful for " + userName);
this.state = CONNECTED; this.state = CONNECTED;
} else if (type.equals(DATA_TYPE_CONFIRM)) { System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
System.out.println("Not expecting to receive a CONFIRM request from client"); userName,
} else if (type.equals(DATA_TYPE_DISCONNECT)) { getConnection().getRemoteHost(),
getConnection().getRemotePort()));
}
/**
* This method is called by method {@link ServerConnectionHandler#processData(Message)}
* Disconnects connection by removing connection from registry and calling method {@link ServerConnectionHandler#stopReceiving()} to terminate socket.
*
* @throws ChatProtocolException if state already DISCONNECTED.
*/
private void caseDisconnect() throws ChatProtocolException {
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)) { }
/**
* This method is called by method {@link ServerConnectionHandler#processData(Message)}
* Checks if broadcast or unicast. Sends data accordingly
*
* @param data to transmit
* @throws ChatProtocolException if state not equal to CONNECT
*/
private void caseMessage(Message data) throws ChatProtocolException {
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(data.getReceiver())) {
for (ServerConnectionHandler handler : connectionRegistry.values()) { for (ServerConnectionHandler handler : connectionRegistry.values()) {
handler.sendData(sender, reciever, type, payload); handler.sendData(data.getSender(), data.getReceiver(), data.getType(), data.getText());
} }
} else { } else {
ServerConnectionHandler handler = connectionRegistry.get(reciever); ServerConnectionHandler handler = connectionRegistry.get(data.getReceiver());
if (handler != null) { if (handler != null) {
handler.sendData(sender, reciever, type, payload); handler.sendData(data.getSender(), data.getReceiver(), data.getType(), data.getText());
if (!data.getReceiver().equals(data.getSender())) {
sendData(data.getSender(), data.getReceiver(), data.getType(), data.getText()); //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: " + data.getReceiver());
}
}
} 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());
} }
} }
} }