Compare commits

..
Author SHA1 Message Date
Andrin Fassbind ad13445978 Start refactoring ClientConnectionHandler.java
ERROR UnsupportedOperationException in ClientMessageList
2022-04-12 21:11:35 +02:00
Andrin Fassbind 88d4493cfb Merge branch 'main' into State_Sync
# Conflicts:
#	client/src/main/java/ch/zhaw/pm2/multichat/client/ChatWindowController.java
#	client/src/main/java/ch/zhaw/pm2/multichat/client/ClientConnectionHandler.java
#	client/src/main/java/ch/zhaw/pm2/multichat/client/ClientMessageList.java
2022-04-12 19:29:11 +02:00
Andrin Fassbind f2fb32bbd4 Start refactoring ClientConnectionHandler.java 2022-04-12 19:22:13 +02:00
Andrin Fassbind f2945b3075 Make State SimpleObjectProperty in ClientConnectionHandler.java
Add changelistener to stateproperty in ChatWindowController.java

fixes Issue #21
2022-04-12 17:44:49 +02:00
7 changed files with 374 additions and 416 deletions
@@ -1,12 +1,12 @@
package ch.zhaw.pm2.multichat.client;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State;
import ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
@@ -16,8 +16,10 @@ import javafx.scene.layout.Pane;
import javafx.stage.WindowEvent;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
public class ChatWindowController {
private ClientConnectionHandler connectionHandler;
@@ -40,24 +42,23 @@ public class ChatWindowController {
public void initialize() {
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT));
}
this.messages = new ClientMessageList();
public void setMessages(ClientMessageList messages) {
this.messages = messages;
messageListener();
}
public void setConnectionHandler(ClientConnectionHandler connectionHandler){
this.connectionHandler = connectionHandler;
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
setMessageField(messages.getMessages());
}
});
}
private void applicationClose() {
disconnect();
connectionHandler.setState(DISCONNECTED);
}
@FXML
private void toggleConnection () {
if (connectionHandler == null || connectionHandler.getStateProperty().get() != CONNECTED) {
if (connectionHandler == null || connectionHandler.getStateObjectProperty().get() != CONNECTED) {
connect();
} else {
disconnect();
@@ -70,19 +71,19 @@ public class ChatWindowController {
startConnectionHandler();
connectionHandler.connect();
} catch(ChatProtocolException | IOException e) {
addError(e.getMessage());
messages.addMessage(null,null, e.getMessage(), Message.MessageType.ERROR);
}
}
private void disconnect() {
if (connectionHandler == null) {
addError("No connection handler");
messages.addMessage(null,null,"No connection handler", Message.MessageType.ERROR);
return;
}
try {
connectionHandler.disconnect();
} catch (ChatProtocolException e) {
addError(e.getMessage());
messages.addMessage(null,null, e.getMessage(), Message.MessageType.ERROR);
}
}
@@ -91,37 +92,43 @@ public class ChatWindowController {
String messageString = messageField.getText().strip();
try {
if (connectionHandler == null) {
addError("No connection handler");
messages.addMessage(null,null,"No connection handler", Message.MessageType.ERROR);
} else if (!connectionHandler.message(messageString)) {
addError("Not a valid message format.");
messages.addMessage(null,null,"Not a valid message format.", Message.MessageType.ERROR);
} else {
messageField.clear();
}
} catch (ChatProtocolException e) {
addError(e.getMessage());
messages.addMessage(null,null, e.getMessage(), Message.MessageType.ERROR);
}
}
//TODO: TEST
@FXML
private void applyFilter( ) {
this.redrawMessageList();
messages.getFilteredMessages(filterValue.getText().strip());
}
private void startConnectionHandler() throws IOException {
String userName = userNameField.getText();
if(!userName.contains(" ")) {
String serverAddress = serverAddressField.getText();
int serverPort = Integer.parseInt(serverPortField.getText());
connectionHandler.initialize(serverAddress, serverPort, userName);
new Thread(connectionHandler).start();
String serverAddress = serverAddressField.getText();
int serverPort = Integer.parseInt(serverPortField.getText());
connectionHandler = new ClientConnectionHandler(messages,serverAddress,serverPort,userName);
new Thread(connectionHandler).start();
//register Listener
startListener();
//register changelistener
startChangeListener();
// register window close handler
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
} else {
addError("It is not allowed to have spaces in username!");
// register window close handler
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
}
private void terminateConnectionHandler() {
// unregister window close handler
rootPane.getScene().getWindow().removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
if (connectionHandler != null) {
connectionHandler.stopReceiving();
connectionHandler = null;
}
}
@@ -133,11 +140,54 @@ public class ChatWindowController {
connectButton.setText((newState == CONNECTED || newState == CONFIRM_DISCONNECT) ? "Disconnect" : "Connect");
}
});
if(newState == DISCONNECTED){
connectionHandler.stopReceiving();
if (newState == DISCONNECTED) {
terminateConnectionHandler();
}
}
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) {
Platform.runLater(new Runnable() {
@Override
@@ -165,10 +215,7 @@ public class ChatWindowController {
});
}
public void addError(String message) {
messages.addMessage(new Message(Message.MessageType.ERROR, null, null, message));
}
//TODO: MAKE ChangeListener
private void redrawMessageList() {
this.messageArea.clear();
Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
@@ -181,43 +228,4 @@ 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;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
@@ -13,59 +13,73 @@ import java.net.SocketException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
import static ch.zhaw.pm2.multichat.client.Message.MessageType.*;
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\S*))?\\s*(.*)$" );
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 SimpleObjectProperty<State> state;
private ClientMessageList messages;
private SimpleStringProperty serverAddress;
private SimpleIntegerProperty serverPort;
private SimpleStringProperty serverAddress;
private ObjectProperty<State> stateObjectProperty;
private ClientMessageList messageList;
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
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);
enum State {
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
}
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));
public ClientConnectionHandler(ClientMessageList messageList,String serverAddress,int serverPort,String userName) throws IOException {
this.stateObjectProperty = new SimpleObjectProperty<>(NEW);
this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName);
this.serverPort = new SimpleIntegerProperty();
this.serverAddress = new SimpleStringProperty();
this.messageList = messageList;
this.connection = NetworkHandler.openConnection(serverAddress,serverPort);
}
public SimpleStringProperty getServerAddressProperty() { return serverAddress; }
public SimpleIntegerProperty getServerPortProperty() { return serverPort; }
public SimpleObjectProperty<State> getStateProperty() {
return this.state;
public ObjectProperty<State> getStateObjectProperty() {
return stateObjectProperty;
}
public SimpleStringProperty getUserNameProperty() { return userName; }
public SimpleStringProperty getUserNameProperty() {
return userName;
}
public SimpleStringProperty getServerAddressProperty() {
return serverAddress;
}
public SimpleIntegerProperty getServerPortProperty() {
return serverPort;
}
public void setState (State newState) {
state.set(newState);
this.stateObjectProperty.set(newState);
}
public void run () {
startReceiving();
}
private void startReceiving() {
public void startReceiving() {
System.out.println("Starting Connection Handler");
try {
System.out.println("Start receiving data...");
while (getConnection().isAvailable()) {
String data = getConnection().receive();
while (connection.isAvailable()) {
String data = connection.receive();
processData(data);
}
System.out.println("Stopped recieving data");
@@ -89,7 +103,7 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
System.out.println("Closing Connection Handler to Server");
try {
System.out.println("Stop receiving data...");
getConnection().close();
connection.close();
System.out.println("Stopped receiving data.");
} catch (IOException e) {
System.err.println("Failed to close connection." + e.getMessage());
@@ -97,90 +111,113 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
System.out.println("Closed Connection Handler to Server");
}
private void processData(String data) {
try {
// parse data content
Scanner scanner = new Scanner(data);
StringBuilder sender = new StringBuilder();
StringBuilder reciever = new StringBuilder();
StringBuilder type = new StringBuilder();
StringBuilder payload = new StringBuilder();
super.processData(scanner,sender,reciever,type,payload);
String sender = null;
String reciever = null;
String type = null;
String payload = null;
if (scanner.hasNextLine()) {
sender = scanner.nextLine();
} else {
throw new ChatProtocolException("No Sender found");
}
if (scanner.hasNextLine()) {
reciever = scanner.nextLine();
} else {
throw new ChatProtocolException("No Reciever found");
}
if (scanner.hasNextLine()) {
type = scanner.nextLine();
} else {
throw new ChatProtocolException("No Type found");
}
if (scanner.hasNextLine()) {
payload = scanner.nextLine();
}
// dispatch operation based on type parameter
if (type.toString().equals(getDataTypeConnect())) {
if (type.equals(DATA_TYPE_CONNECT)) {
System.err.println("Illegal connect request from server");
} else if (type.toString().equals(getDataTypeConfirm())) {
caseConfirm(sender.toString(), reciever.toString(), payload.toString());
} else if (type.toString().equals(getDataTypeDisconnect())) {
caseDisconnect(sender.toString(),reciever.toString(),payload.toString());
} else if (type.toString().equals(getDataTypeMessage())) {
caseMessage(sender.toString(),reciever.toString(),payload.toString());
} else if (type.toString().equals(getDataTypeError())) {
caseError(sender.toString(), reciever.toString(), payload.toString());
} else if (type.equals(DATA_TYPE_CONFIRM)) {
if (stateObjectProperty.get() == CONFIRM_CONNECT) {
this.userName.set(reciever);
this.serverAddress.set(connection.getRemoteHost());
this.serverPort.set(connection.getRemotePort());
messageList.addMessage(sender,reciever,payload,INFO);
System.out.println("CONFIRM: " + payload);
this.setState(CONNECTED);
} else if (stateObjectProperty.get() == CONFIRM_DISCONNECT) {
messageList.addMessage(sender,reciever,payload,INFO);
System.out.println("CONFIRM: " + payload);
this.setState(DISCONNECTED);
} else {
System.err.println("Got unexpected confirm message: " + payload);
}
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
if (stateObjectProperty.get() == DISCONNECTED) {
System.out.println("DISCONNECT: Already in disconnected: " + payload);
return;
}
messageList.addMessage(sender,reciever,payload,INFO);
System.out.println("DISCONNECT: " + payload);
this.setState(DISCONNECTED);
} else if (type.equals(DATA_TYPE_MESSAGE)) {
if (stateObjectProperty.get() != CONNECTED) {
System.out.println("MESSAGE: Illegal state " + stateObjectProperty.get() + " for message: " + payload);
return;
}
messageList.addMessage(sender,reciever,payload,MESSAGE);
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
} else if (type.equals(DATA_TYPE_ERROR)) {
messageList.addMessage(sender,reciever,payload,ERROR);
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.get(), getDataTypeError(), e.getMessage());
sendData(USER_NONE, userName.get(), DATA_TYPE_ERROR, e.getMessage());
}
}
private void caseConfirm(String sender, String reciever, String payload) {
if (state.get() == CONFIRM_CONNECT) {
this.userName.set(reciever);
this.serverPort.set(getConnection().getRemotePort());
this.serverAddress.set(getConnection().getRemoteHost());
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
System.out.println("CONFIRM: " + payload);
this.setState(CONNECTED);
} else if (state.get() == CONFIRM_DISCONNECT) {
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
System.out.println("CONFIRM: " + payload);
this.setState(DISCONNECTED);
} else {
System.err.println("Got unexpected confirm message: " + payload);
public void sendData(String sender, String receiver, String type, String payload) {
if (connection.isAvailable()) {
new StringBuilder();
String data = new StringBuilder()
.append(sender+"\n")
.append(receiver+"\n")
.append(type+"\n")
.append(payload+"\n")
.toString();
try {
connection.send(data);
} catch (SocketException e) {
System.err.println("Connection closed: " + e.getMessage());
} catch (EOFException e) {
System.out.println("Connection terminated by remote");
} catch(IOException e) {
System.err.println("Communication error: " + e.getMessage());
}
}
}
private void caseDisconnect(String sender, String reciever, String payload) {
if (state.get() == DISCONNECTED) {
System.out.println("DISCONNECT: Already in disconnected: " + payload);
return;
}
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
System.out.println("DISCONNECT: " + payload);
this.setState(DISCONNECTED);
}
private void caseMessage(String sender, String reciever, String payload) {
if (state.get() != CONNECTED) {
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
return;
}
messages.addMessage(new Message(Message.MessageType.MESSAGE,sender,reciever,payload));
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
}
private void caseError(String sender, String reciever, String payload) {
messages.addMessage(new Message(Message.MessageType.ERROR,sender,reciever,payload));
System.out.println("ERROR: " + payload);
}
public void connect() throws ChatProtocolException {
if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
this.sendData(userName.get(), USER_NONE, getDataTypeConnect(),null);
if (stateObjectProperty.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + stateObjectProperty.get());
this.sendData(userName.get(), USER_NONE, DATA_TYPE_CONNECT,null);
this.setState(CONFIRM_CONNECT);
}
public void disconnect() throws ChatProtocolException {
if (state.get() != NEW && state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + state);
this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(),null);
if (stateObjectProperty.get() != NEW && stateObjectProperty.get() != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + stateObjectProperty.get());
this.sendData(userName.get(), USER_NONE, DATA_TYPE_DISCONNECT,null);
this.setState(CONFIRM_DISCONNECT);
}
public boolean message(String messageString) throws ChatProtocolException {
if (state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state);
if (stateObjectProperty.get() != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + stateObjectProperty.get());
Matcher matcher = messagePattern.matcher(messageString);
if (matcher.find()) {
@@ -190,10 +227,11 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
return false;
}
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
this.sendData(userName.get(), receiver, getDataTypeMessage(),message);
this.sendData(userName.get(), receiver, DATA_TYPE_MESSAGE,message);
return true;
} else {
return false;
}
}
}
@@ -1,17 +1,34 @@
package ch.zhaw.pm2.multichat.client;
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.List;
public class ClientMessageList {
private List<Message> messages = new ArrayList<>();
private SimpleBooleanProperty changed = new SimpleBooleanProperty(false);
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.USER_NONE;
public void addMessage(Message message) {
messages.add(message);
changed.set(!changed.get());
public class ClientMessageList {
private List<Message> messages;
private SimpleBooleanProperty changed;
public ClientMessageList() {
messages = new ArrayList<>();
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());
}
public String getFilteredMessages(String filter) {
@@ -31,11 +48,21 @@ public class ClientMessageList {
return result.toString();
}
public void clear() {
messages = new ArrayList<>();
changed.set(!changed.get());
public String getMessages() {
StringBuilder result = new StringBuilder();
for(Message message : messages) {
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 SimpleBooleanProperty getChangedProperty() { return changed; }
public void clear() {
messages = new SimpleListProperty<>();
}
}
@@ -8,7 +8,6 @@ import javafx.stage.Stage;
public class ClientUI extends Application {
private ClientMessageList clientMessageList = new ClientMessageList();
private ClientConnectionHandler connectionHandler = new ClientConnectionHandler(clientMessageList);
@Override
public void start(Stage primaryStage) {
@@ -18,11 +17,8 @@ public class ClientUI extends Application {
private void chatWindow(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("ChatWindow.fxml"));
Pane rootPane = loader.load();
ChatWindowController chatWindowController = loader.getController();
chatWindowController.setMessages(clientMessageList);
chatWindowController.setConnectionHandler(connectionHandler);
Pane rootPane = loader.load();
// fill in scene and stage setup
Scene scene = new Scene(rootPane);
@@ -1,95 +0,0 @@
package ch.zhaw.pm2.multichat.protocol;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketException;
import java.util.Scanner;
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, ERROR;
}
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(NetworkHandler.NetworkConnection<String> connection) {
this.connection = connection;
}
protected void processData(Scanner scanner, StringBuilder sender, StringBuilder reciever, StringBuilder type, StringBuilder payload) throws ChatProtocolException {
// parse data content
if (scanner.hasNextLine()) {
sender.append(scanner.nextLine());
} else {
throw new ChatProtocolException("No Sender found");
}
if (scanner.hasNextLine()) {
reciever.append(scanner.nextLine());
} else {
throw new ChatProtocolException("No Reciever found");
}
if (scanner.hasNextLine()) {
type.append(scanner.nextLine());
} else {
throw new ChatProtocolException("No Type found");
}
if (scanner.hasNextLine()) {
payload.append(scanner.nextLine());
}
}
protected 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 {
getConnection().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());
}
}
}
}
@@ -1,14 +1,11 @@
package ch.zhaw.pm2.multichat.server;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Server {
@@ -65,40 +62,23 @@ public class Server {
}
private void start() {
ReentrantLock mutex = new ReentrantLock();
Condition nameComplete = mutex.newCondition();
System.out.println("Server started.");
try {
while (true) {
NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection();
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections, mutex, nameComplete);
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections);
new Thread(connectionHandler).start();
mutex.lock();
try {
nameComplete.await();
if(connectionHandler.getState() == ConnectionHandler.State.ERROR) {
System.out.println(String.format("Connecting failed for new Client with IP:Port <%s:%d>.\nReason: Name already taken.",
connection.getRemoteHost(),
connection.getRemotePort()));
}
else {
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
connectionHandler.getUserName(),
connection.getRemoteHost(),
connection.getRemotePort()));
}
}
finally {
mutex.unlock();
}
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
connectionHandler.getUserName(),
connection.getRemoteHost(),
connection.getRemotePort()
));
}
} catch(SocketException e) {
System.out.println("Server connection terminated");
}
catch (IOException e) {
System.err.println("Communication error " + e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// close server
System.out.println("Server Stopped.");
@@ -1,30 +1,34 @@
package ch.zhaw.pm2.multichat.server;
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.NetworkHandler;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
public class ServerConnectionHandler extends ConnectionHandler implements Runnable{
public class ServerConnectionHandler implements Runnable{
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
private final int connectionId = connectionCounter.incrementAndGet();
private final NetworkHandler.NetworkConnection<String> connection;
private final Map<String,ServerConnectionHandler> connectionRegistry;
private ReentrantLock mutex;
// Data types used for the Chat Protocol
private static final String DATA_TYPE_CONNECT = "CONNECT";
private static final String DATA_TYPE_CONFIRM = "CONFIRM";
private static final String DATA_TYPE_DISCONNECT = "DISCONNECT";
private static final String DATA_TYPE_MESSAGE = "MESSAGE";
private static final String DATA_TYPE_ERROR = "ERROR";
private Condition nameComplete;
private static final String USER_NONE = "";
private static final String USER_ALL = "*";
private String userName = "Anonymous-"+connectionId;
private State state = NEW;
@@ -34,150 +38,150 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
startReceiving();
}
enum State {
NEW, CONNECTED, DISCONNECTED;
}
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
Map<String,ServerConnectionHandler> registry, ReentrantLock mutex, Condition nameComplete) {
super();
setConnection(connection);
Map<String,ServerConnectionHandler> registry) {
Objects.requireNonNull(connection, "Connection must not be null");
Objects.requireNonNull(registry, "Registry must not be null");
this.connection = connection;
this.connectionRegistry = registry;
this.mutex = mutex;
this.nameComplete = nameComplete;
}
public String getUserName() {
return this.userName;
}
public State getState() {
return state;
}
private void startReceiving() {
System.out.println("Starting Connection Handler for new User");
try {
System.out.println("Start receiving data...");
while (getConnection().isAvailable() && !(state == ERROR)) {
String data = getConnection().receive();
processData(data);
}
System.out.println("Stopped recieving data");
} catch (SocketException e) {
System.out.println("Connection terminated locally");
connectionRegistry.remove(userName);
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
} catch (EOFException e) {
System.out.println("Connection terminated by remote");
connectionRegistry.remove(userName);
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
} catch (IOException e) {
System.err.println("Communication error: " + e);
} catch (ClassNotFoundException e) {
System.err.println("Received object of unknown type: " + e.getMessage());
public void startReceiving() {
System.out.println("Starting Connection Handler for " + userName);
try {
System.out.println("Start receiving data...");
while (connection.isAvailable()) {
String data = connection.receive();
processData(data);
}
if (state == ERROR) {
System.out.println("Stopping Connection Handler for Rejected Client");
} else {
System.out.println("Stopping Connection Handler for " + userName);
System.out.println("Stopped recieving data");
} catch (SocketException e) {
System.out.println("Connection terminated locally");
connectionRegistry.remove(userName);
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
} catch (EOFException e) {
System.out.println("Connection terminated by remote");
connectionRegistry.remove(userName);
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
} catch(IOException e) {
System.err.println("Communication error: " + e);
} catch(ClassNotFoundException e) {
System.err.println("Received object of unknown type: " + e.getMessage());
}
System.out.println("Stopping Connection Handler for " + userName);
}
private void stopReceiving() {
public void stopReceiving() {
System.out.println("Closing Connection Handler for " + userName);
try {
System.out.println("Stop receiving data...");
getConnection().close();
connection.close();
System.out.println("Stopped receiving data.");
} catch (IOException e) {
System.err.println("Failed to close connection." + e.getMessage());
System.err.println("Failed to close connection." + e);
}
System.out.println("Closed Connection Handler for " + userName);
}
private void processData(String data) {
try {
// parse data content
Scanner scanner = new Scanner(data);
StringBuilder sender = new StringBuilder();
StringBuilder reciever = new StringBuilder();
StringBuilder type = new StringBuilder();
StringBuilder payload = new StringBuilder();
super.processData(scanner,sender,reciever,type,payload);
String sender = null;
String reciever = null;
String type = null;
String payload = null;
if (scanner.hasNextLine()) {
sender = scanner.nextLine();
} else {
throw new ChatProtocolException("No Sender found");
}
if (scanner.hasNextLine()) {
reciever = scanner.nextLine();
} else {
throw new ChatProtocolException("No Reciever found");
}
if (scanner.hasNextLine()) {
type = scanner.nextLine();
} else {
throw new ChatProtocolException("No Type found");
}
if (scanner.hasNextLine()) {
payload = scanner.nextLine();
}
// dispatch operation based on type parameter
if (type.toString().equals(getDataTypeConnect())) {
caseConnect(sender.toString());
} else if (type.toString().equals(getDataTypeConfirm())) {
if (type.equals(DATA_TYPE_CONNECT)) {
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
if (sender == null || sender.isBlank()) sender = this.userName;
if (connectionRegistry.containsKey(sender))
throw new ChatProtocolException("User name already taken: " + sender);
this.userName = sender;
connectionRegistry.put(userName, this);
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Registration successfull for " + userName);
this.state = CONNECTED;
} else if (type.equals(DATA_TYPE_CONFIRM)) {
System.out.println("Not expecting to receive a CONFIRM request from client");
} else if (type.toString().equals(getDataTypeDisconnect())) {
caseDisconnect();
} else if (type.toString().equals(getDataTypeMessage())) {
caseMessage(sender.toString(), reciever.toString(), type.toString(), payload.toString());
} else if (type.toString().equals(getDataTypeError())) {
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
if (state == DISCONNECTED)
throw new ChatProtocolException("Illegal state for disconnect request: " + state);
if (state == CONNECTED) {
connectionRegistry.remove(this.userName);
}
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Confirm disconnect of " + userName);
this.state = DISCONNECTED;
this.stopReceiving();
} else if (type.equals(DATA_TYPE_MESSAGE)) {
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state);
if (USER_ALL.equals(reciever)) {
for (ServerConnectionHandler handler : connectionRegistry.values()) {
handler.sendData(sender, reciever, type, payload);
}
} else {
ServerConnectionHandler handler = connectionRegistry.get(reciever);
if (handler != null) {
handler.sendData(sender, reciever, type, payload);
} else {
this.sendData(USER_NONE, userName, DATA_TYPE_ERROR, "Unknown User: " + reciever);
}
}
} else if (type.equals(DATA_TYPE_ERROR)) {
System.err.println("Received error from client (" + sender + "): " + payload);
} else {
System.err.println("Unknown data type received: " + type);
}
} catch(ChatProtocolException e) {
System.out.println("Error while processing data " + e.getMessage());
sendData(USER_NONE, userName, getDataTypeError(), e.getMessage());
System.out.println("Error while processing data" + e.getMessage());
sendData(USER_NONE, userName, DATA_TYPE_ERROR, e.getMessage());
}
}
private void caseConnect(String sender) throws ChatProtocolException {
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
if (sender.isBlank()) sender = this.userName;
if (connectionRegistry.containsKey(sender)) {
mutex.lock();
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 {
state = ERROR;
nameComplete.signal();
}
finally {
mutex.unlock();
}
throw new ChatProtocolException("User name already taken: " + sender);
}
mutex.lock();
try {
this.userName = sender.toString();
nameComplete.signal();
}
finally {
mutex.unlock();
}
connectionRegistry.put(userName, this);
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
this.state = CONNECTED;
}
private void caseDisconnect() throws ChatProtocolException {
if (state == DISCONNECTED)
throw new ChatProtocolException("Illegal state for disconnect request: " + state);
if (state == CONNECTED) {
connectionRegistry.remove(this.userName);
}
sendData(USER_NONE, userName, getDataTypeConfirm(), "Confirm disconnect of " + userName);
this.state = DISCONNECTED;
this.stopReceiving();
}
private void caseMessage(String sender, String reciever, String type, String payload) throws ChatProtocolException{
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state);
if (USER_ALL.equals(reciever)) {
for (ServerConnectionHandler handler : connectionRegistry.values()) {
handler.sendData(sender, reciever, type, payload);
}
} else {
ServerConnectionHandler handler = connectionRegistry.get(reciever);
if (handler != null) {
handler.sendData(sender, reciever, type, payload);
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 {
this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + reciever);
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());
}
}
}