Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a534b2465 | ||
|
|
37045ade15 | ||
|
|
a75d3466ef | ||
|
|
97b6fff82e | ||
|
|
2a8b701f48 | ||
|
|
86aa801b34 | ||
|
|
2277fee73a | ||
|
|
d8dbd93c15 | ||
|
|
6e8e560d73 | ||
|
|
5a26c6b127 | ||
|
|
615b3844e3 | ||
|
|
5e6e9d5817 | ||
|
|
4a998b0f61 | ||
|
|
af46e499ff | ||
|
|
b6fd5b569d | ||
|
|
8c588ee75c | ||
|
|
800528cc37 | ||
|
|
b47d98b960 | ||
|
|
886d9e5e43 | ||
|
|
7c68472859 | ||
|
|
b9ffb2b133 | ||
|
|
e69ced4081 | ||
|
|
d1dfe6c1ab | ||
|
|
3eedf58685 | ||
|
|
1777b62582 | ||
|
|
a0b7b363c3 | ||
|
|
914fa8f1e2 | ||
|
|
9eb352c0fe | ||
|
|
a27b7f4446 | ||
|
|
1a188f6bbd | ||
|
|
56200b749d | ||
|
|
7e7333dfaf | ||
|
|
3082da8a91 | ||
|
|
424a174847 | ||
|
|
b246c3c7e3 | ||
|
|
eb0e6d0dbc | ||
|
|
0896257fad | ||
|
|
e11fb136cf |
@@ -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.State;
|
||||||
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
||||||
|
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
|
||||||
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
|
import javafx.beans.value.ChangeListener;
|
||||||
|
import javafx.beans.value.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,13 +16,10 @@ import javafx.scene.layout.Pane;
|
|||||||
import javafx.stage.WindowEvent;
|
import javafx.stage.WindowEvent;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.regex.Matcher;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
|
|
||||||
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
|
||||||
|
|
||||||
public class ChatWindowController {
|
public class ChatWindowController {
|
||||||
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
|
|
||||||
private ClientConnectionHandler connectionHandler;
|
private ClientConnectionHandler connectionHandler;
|
||||||
private ClientMessageList messages;
|
private ClientMessageList messages;
|
||||||
|
|
||||||
@@ -40,17 +40,24 @@ public class ChatWindowController {
|
|||||||
public void initialize() {
|
public void initialize() {
|
||||||
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
|
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
|
||||||
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT));
|
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT));
|
||||||
stateChanged(NEW);
|
}
|
||||||
messages = new ClientMessageList(this);
|
|
||||||
|
public void setMessages(ClientMessageList messages) {
|
||||||
|
this.messages = messages;
|
||||||
|
messageListener();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setConnectionHandler(ClientConnectionHandler connectionHandler){
|
||||||
|
this.connectionHandler = connectionHandler;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void applicationClose() {
|
private void applicationClose() {
|
||||||
connectionHandler.setState(DISCONNECTED);
|
disconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@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();
|
||||||
@@ -59,46 +66,39 @@ public class ChatWindowController {
|
|||||||
|
|
||||||
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(e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@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();
|
try {
|
||||||
Matcher matcher = messagePattern.matcher(messageString);
|
if (connectionHandler == null) {
|
||||||
if (matcher.find()) {
|
addError("No connection handler");
|
||||||
String receiver = matcher.group(1);
|
} else if (!connectionHandler.message(messageString)) {
|
||||||
String message = matcher.group(2);
|
addError("Not a valid message format.");
|
||||||
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
|
} else {
|
||||||
try {
|
messageField.clear();
|
||||||
connectionHandler.message(receiver, message);
|
|
||||||
} catch (ChatProtocolException e) {
|
|
||||||
writeError(e.getMessage());
|
|
||||||
}
|
}
|
||||||
} else {
|
} catch (ChatProtocolException e) {
|
||||||
writeError("Not a valid message format.");
|
addError(e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,23 +109,19 @@ public class ChatWindowController {
|
|||||||
|
|
||||||
private void startConnectionHandler() throws IOException {
|
private void startConnectionHandler() throws IOException {
|
||||||
String userName = userNameField.getText();
|
String userName = userNameField.getText();
|
||||||
String serverAddress = serverAddressField.getText();
|
if(!userName.contains(" ")) {
|
||||||
int serverPort = Integer.parseInt(serverPortField.getText());
|
String serverAddress = serverAddressField.getText();
|
||||||
connectionHandler = new ClientConnectionHandler(
|
int serverPort = Integer.parseInt(serverPortField.getText());
|
||||||
NetworkHandler.openConnection(serverAddress, serverPort), userName,
|
connectionHandler.initialize(serverAddress, serverPort, userName);
|
||||||
this);
|
new Thread(connectionHandler).start();
|
||||||
new Thread(connectionHandler).start();
|
|
||||||
|
|
||||||
// register window close handler
|
//register Listener
|
||||||
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
startListener();
|
||||||
}
|
|
||||||
|
|
||||||
private void terminateConnectionHandler() {
|
// register window close handler
|
||||||
// unregister window close handler
|
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
||||||
rootPane.getScene().getWindow().removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
} else {
|
||||||
if (connectionHandler != null) {
|
addError("It is not allowed to have spaces in username!");
|
||||||
connectionHandler.stopReceiving();
|
|
||||||
connectionHandler = null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,8 +133,8 @@ public class ChatWindowController {
|
|||||||
connectButton.setText((newState == CONNECTED || newState == CONFIRM_DISCONNECT) ? "Disconnect" : "Connect");
|
connectButton.setText((newState == CONNECTED || newState == CONFIRM_DISCONNECT) ? "Disconnect" : "Connect");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (newState == DISCONNECTED) {
|
if(newState == DISCONNECTED){
|
||||||
terminateConnectionHandler();
|
connectionHandler.stopReceiving();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,43 +165,15 @@ public class ChatWindowController {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addMessage(String sender, String receiver, String message) {
|
|
||||||
messages.addMessage(ClientMessageList.MessageType.MESSAGE, sender, receiver, message);
|
|
||||||
this.redrawMessageList();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addInfo(String message) {
|
|
||||||
messages.addMessage(ClientMessageList.MessageType.INFO, null, null, message);
|
|
||||||
this.redrawMessageList();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addError(String message) {
|
public void addError(String message) {
|
||||||
messages.addMessage(ClientMessageList.MessageType.ERROR, null, null, message);
|
messages.addMessage(new Message(Message.MessageType.ERROR, null, null, message));
|
||||||
this.redrawMessageList();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void clearMessageArea() {
|
|
||||||
this.messageArea.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private void redrawMessageList() {
|
private void redrawMessageList() {
|
||||||
Platform.runLater(() -> messages.writeFilteredMessages(filterValue.getText().strip()));
|
this.messageArea.clear();
|
||||||
|
Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(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> {
|
||||||
public void handle(WindowEvent event) {
|
public void handle(WindowEvent event) {
|
||||||
applicationClose();
|
applicationClose();
|
||||||
@@ -213,7 +181,43 @@ public class ChatWindowController {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void startListener() {
|
||||||
|
connectionHandler.getStateProperty().addListener(new ChangeListener<State>() {
|
||||||
|
@Override
|
||||||
|
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
|
||||||
|
stateChanged(newValue);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
connectionHandler.getUserNameProperty().addListener(new ChangeListener<String>() {
|
||||||
|
@Override
|
||||||
|
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
|
||||||
|
setUserName(newValue);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
connectionHandler.getServerAddressProperty().addListener(new ChangeListener<String>() {
|
||||||
|
@Override
|
||||||
|
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
|
||||||
|
setServerAddress(newValue);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
connectionHandler.getServerPortProperty().addListener(new ChangeListener<Number>() {
|
||||||
|
@Override
|
||||||
|
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
|
||||||
|
setServerPort(newValue.intValue());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void messageListener() {
|
||||||
|
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
|
||||||
|
@Override
|
||||||
|
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
|
||||||
|
redrawMessageList();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,63 +1,71 @@
|
|||||||
package ch.zhaw.pm2.multichat.client;
|
package ch.zhaw.pm2.multichat.client;
|
||||||
|
|
||||||
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
||||||
|
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
|
||||||
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||||
|
import javafx.beans.property.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.protocol.ConnectionHandler.State.*;
|
||||||
|
|
||||||
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
|
||||||
|
|
||||||
public class ClientConnectionHandler implements Runnable {
|
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\S*))?\\s*(.*)$" );
|
||||||
private final NetworkHandler.NetworkConnection<String> connection;
|
|
||||||
private final ChatWindowController controller;
|
|
||||||
|
|
||||||
// Data types used for the Chat Protocol
|
private SimpleStringProperty userName;
|
||||||
private static final String DATA_TYPE_CONNECT = "CONNECT";
|
private SimpleObjectProperty<State> state;
|
||||||
private static final String DATA_TYPE_CONFIRM = "CONFIRM";
|
private ClientMessageList messages;
|
||||||
private static final String DATA_TYPE_DISCONNECT = "DISCONNECT";
|
private SimpleStringProperty serverAddress;
|
||||||
private static final String DATA_TYPE_MESSAGE = "MESSAGE";
|
private SimpleIntegerProperty serverPort;
|
||||||
private static final String DATA_TYPE_ERROR = "ERROR";
|
|
||||||
|
|
||||||
public static final String USER_NONE = "";
|
public ClientConnectionHandler(ClientMessageList messages) {
|
||||||
public static final String USER_ALL = "*";
|
super();
|
||||||
|
this.messages = messages;
|
||||||
private String userName = USER_NONE;
|
state = new SimpleObjectProperty<>(State.NEW);
|
||||||
private State state = NEW;
|
serverAddress = new SimpleStringProperty(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
|
||||||
|
serverPort = new SimpleIntegerProperty(NetworkHandler.DEFAULT_PORT);
|
||||||
enum State {
|
this.userName = new SimpleStringProperty(null);
|
||||||
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
public void initialize(String serverAddress, int serverPort, String userName) throws IOException {
|
||||||
String userName,
|
state.set(NEW);
|
||||||
ChatWindowController controller) {
|
this.serverAddress.set(serverAddress);
|
||||||
this.connection = connection;
|
this.serverPort.set(serverPort);
|
||||||
this.userName = (userName == null || userName.isBlank())? USER_NONE : userName;
|
setConnection(NetworkHandler.openConnection(serverAddress, serverPort));
|
||||||
this.controller = controller;
|
this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName);
|
||||||
}
|
}
|
||||||
|
|
||||||
public State getState() {
|
public SimpleStringProperty getServerAddressProperty() { return serverAddress; }
|
||||||
|
|
||||||
|
public SimpleIntegerProperty getServerPortProperty() { return serverPort; }
|
||||||
|
|
||||||
|
public SimpleObjectProperty<State> getStateProperty() {
|
||||||
return this.state;
|
return this.state;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public SimpleStringProperty getUserNameProperty() { return userName; }
|
||||||
|
|
||||||
public void setState (State newState) {
|
public void setState (State newState) {
|
||||||
this.state = newState;
|
state.set(newState);
|
||||||
controller.stateChanged(newState);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void run () {
|
public void run () {
|
||||||
startReceiving();
|
startReceiving();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void startReceiving() {
|
private void startReceiving() {
|
||||||
System.out.println("Starting Connection Handler");
|
System.out.println("Starting Connection Handler");
|
||||||
try {
|
try {
|
||||||
System.out.println("Start receiving data...");
|
System.out.println("Start receiving data...");
|
||||||
while (connection.isAvailable()) {
|
while (getConnection().isAvailable()) {
|
||||||
String data = connection.receive();
|
String data = getConnection().receive();
|
||||||
processData(data);
|
processData(data);
|
||||||
}
|
}
|
||||||
System.out.println("Stopped recieving data");
|
System.out.println("Stopped recieving data");
|
||||||
@@ -81,7 +89,7 @@ public class ClientConnectionHandler implements Runnable {
|
|||||||
System.out.println("Closing Connection Handler to Server");
|
System.out.println("Closing Connection Handler to Server");
|
||||||
try {
|
try {
|
||||||
System.out.println("Stop receiving data...");
|
System.out.println("Stop receiving data...");
|
||||||
connection.close();
|
getConnection().close();
|
||||||
System.out.println("Stopped receiving data.");
|
System.out.println("Stopped receiving data.");
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("Failed to close connection." + e.getMessage());
|
System.err.println("Failed to close connection." + e.getMessage());
|
||||||
@@ -91,112 +99,101 @@ public class ClientConnectionHandler implements Runnable {
|
|||||||
|
|
||||||
private void processData(String data) {
|
private void processData(String data) {
|
||||||
try {
|
try {
|
||||||
// parse data content
|
|
||||||
Scanner scanner = new Scanner(data);
|
Scanner scanner = new Scanner(data);
|
||||||
String sender = null;
|
StringBuilder sender = new StringBuilder();
|
||||||
String reciever = null;
|
StringBuilder reciever = new StringBuilder();
|
||||||
String type = null;
|
StringBuilder type = new StringBuilder();
|
||||||
String payload = null;
|
StringBuilder payload = new StringBuilder();
|
||||||
if (scanner.hasNextLine()) {
|
super.processData(scanner,sender,reciever,type,payload);
|
||||||
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 (type.toString().equals(getDataTypeConnect())) {
|
||||||
System.err.println("Illegal connect request from server");
|
System.err.println("Illegal connect request from server");
|
||||||
} else if (type.equals(DATA_TYPE_CONFIRM)) {
|
} else if (type.toString().equals(getDataTypeConfirm())) {
|
||||||
if (state == CONFIRM_CONNECT) {
|
caseConfirm(sender.toString(), reciever.toString(), payload.toString());
|
||||||
this.userName = reciever;
|
} else if (type.toString().equals(getDataTypeDisconnect())) {
|
||||||
controller.setUserName(userName);
|
caseDisconnect(sender.toString(),reciever.toString(),payload.toString());
|
||||||
controller.setServerPort(connection.getRemotePort());
|
} else if (type.toString().equals(getDataTypeMessage())) {
|
||||||
controller.setServerAddress(connection.getRemoteHost());
|
caseMessage(sender.toString(),reciever.toString(),payload.toString());
|
||||||
controller.addInfo(payload);
|
} else if (type.toString().equals(getDataTypeError())) {
|
||||||
System.out.println("CONFIRM: " + payload);
|
caseError(sender.toString(), reciever.toString(), payload.toString());
|
||||||
this.setState(CONNECTED);
|
|
||||||
} else if (state == CONFIRM_DISCONNECT) {
|
|
||||||
controller.addInfo(payload);
|
|
||||||
System.out.println("CONFIRM: " + payload);
|
|
||||||
this.setState(DISCONNECTED);
|
|
||||||
} else {
|
|
||||||
System.err.println("Got unexpected confirm message: " + payload);
|
|
||||||
}
|
|
||||||
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
|
|
||||||
if (state == DISCONNECTED) {
|
|
||||||
System.out.println("DISCONNECT: Already in disconnected: " + payload);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
controller.addInfo(payload);
|
|
||||||
System.out.println("DISCONNECT: " + payload);
|
|
||||||
this.setState(DISCONNECTED);
|
|
||||||
} else if (type.equals(DATA_TYPE_MESSAGE)) {
|
|
||||||
if (state != CONNECTED) {
|
|
||||||
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
controller.addMessage(sender, reciever, payload);
|
|
||||||
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
|
|
||||||
} else if (type.equals(DATA_TYPE_ERROR)) {
|
|
||||||
controller.addError(payload);
|
|
||||||
System.out.println("ERROR: " + payload);
|
|
||||||
} else {
|
} else {
|
||||||
System.out.println("Unknown data type received: " + type);
|
System.out.println("Unknown data type received: " + type);
|
||||||
}
|
}
|
||||||
} catch (ChatProtocolException e) {
|
} catch (ChatProtocolException e) {
|
||||||
System.err.println("Error while processing data: " + e.getMessage());
|
System.err.println("Error while processing data: " + e.getMessage());
|
||||||
sendData(USER_NONE, userName, DATA_TYPE_ERROR, e.getMessage());
|
sendData(USER_NONE, userName.get(), getDataTypeError(), e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void sendData(String sender, String receiver, String type, String payload) {
|
private void caseConfirm(String sender, String reciever, String payload) {
|
||||||
if (connection.isAvailable()) {
|
if (state.get() == CONFIRM_CONNECT) {
|
||||||
new StringBuilder();
|
this.userName.set(reciever);
|
||||||
String data = new StringBuilder()
|
this.serverPort.set(getConnection().getRemotePort());
|
||||||
.append(sender+"\n")
|
this.serverAddress.set(getConnection().getRemoteHost());
|
||||||
.append(receiver+"\n")
|
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
|
||||||
.append(type+"\n")
|
System.out.println("CONFIRM: " + payload);
|
||||||
.append(payload+"\n")
|
this.setState(CONNECTED);
|
||||||
.toString();
|
} else if (state.get() == CONFIRM_DISCONNECT) {
|
||||||
try {
|
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
|
||||||
connection.send(data);
|
System.out.println("CONFIRM: " + payload);
|
||||||
} catch (SocketException e) {
|
this.setState(DISCONNECTED);
|
||||||
System.err.println("Connection closed: " + e.getMessage());
|
} else {
|
||||||
} catch (EOFException e) {
|
System.err.println("Got unexpected confirm message: " + payload);
|
||||||
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 {
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
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) throw new ChatProtocolException("Illegal state for disconnect: " + state);
|
||||||
this.sendData(userName, USER_NONE, DATA_TYPE_DISCONNECT,null);
|
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 {
|
public boolean message(String messageString) throws ChatProtocolException {
|
||||||
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state);
|
if (state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state);
|
||||||
this.sendData(userName, receiver, DATA_TYPE_MESSAGE,message);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
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,41 @@
|
|||||||
package ch.zhaw.pm2.multichat.client;
|
package ch.zhaw.pm2.multichat.client;
|
||||||
|
|
||||||
|
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;
|
|
||||||
|
|
||||||
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 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) {
|
public void addMessage(Message message) {
|
||||||
this.gui = gui;
|
messages.add(message);
|
||||||
}
|
changed.set(!changed.get());
|
||||||
|
|
||||||
public void addMessage(MessageType type, String sender, String receiver, String message) {
|
|
||||||
typeList.add(type);
|
|
||||||
senderList.add(sender);
|
|
||||||
receiverList.add(receiver);
|
|
||||||
messageList.add(message);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void writeFilteredMessages(String filter) {
|
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),"");
|
|
||||||
String receiver = Objects.requireNonNullElse(receiverList.get(i),"");
|
|
||||||
String message = Objects.requireNonNull(messageList.get(i), "");
|
|
||||||
if(showAll ||
|
|
||||||
sender.contains(filter) ||
|
|
||||||
receiver.contains(filter) ||
|
|
||||||
message.contains(filter))
|
|
||||||
{
|
{
|
||||||
switch (typeList.get(i)) {
|
switch (message.getType()) {
|
||||||
case MESSAGE: gui.writeMessage(senderList.get(i), receiverList.get(i), messageList.get(i)); break;
|
case MESSAGE -> result.append(String.format("[%s -> %s] %s\n", message.getSender(), message.getReceiver(), message.getText()));
|
||||||
case ERROR: gui.writeError(messageList.get(i)); break;
|
case ERROR -> result.append(String.format("[ERROR] %s\n", message.getText()));
|
||||||
case INFO: gui.writeInfo(messageList.get(i)); break;
|
case INFO -> result.append(String.format("[INFO] %s\n", message.getText()));
|
||||||
default: gui.writeError("Unexpected message type: " + typeList.get(i));
|
default -> result.append(String.format("[ERROR] %s\n", "Unexpected message type: " + message.getType()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return result.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum MessageType {
|
public void clear() {
|
||||||
INFO, MESSAGE, ERROR;
|
messages = new ArrayList<>();
|
||||||
|
changed.set(!changed.get());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public SimpleBooleanProperty getChangedProperty() { return changed; }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import javafx.scene.layout.Pane;
|
|||||||
import javafx.stage.Stage;
|
import javafx.stage.Stage;
|
||||||
|
|
||||||
public class ClientUI extends Application {
|
public class ClientUI extends Application {
|
||||||
|
private ClientMessageList clientMessageList = new ClientMessageList();
|
||||||
|
private ClientConnectionHandler connectionHandler = new ClientConnectionHandler(clientMessageList);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start(Stage primaryStage) {
|
public void start(Stage primaryStage) {
|
||||||
@@ -17,6 +19,11 @@ public class ClientUI extends Application {
|
|||||||
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());
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package ch.zhaw.pm2.multichat.client;
|
||||||
|
|
||||||
|
/**
|
||||||
|
A Message object represents one Message of a client. Can be stored in ClientMessageList.
|
||||||
|
*/
|
||||||
|
public class Message {
|
||||||
|
private MessageType type;
|
||||||
|
private String sender;
|
||||||
|
private String receiver;
|
||||||
|
private 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 reciever will be null)
|
||||||
|
* @param sender The User who has sent the message.
|
||||||
|
* @param receiver The User who should recieve the message.
|
||||||
|
* @param text The Text of the message.
|
||||||
|
*/
|
||||||
|
public Message(MessageType 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 datafields sender, receiver or text
|
||||||
|
* @param filter The Filter String
|
||||||
|
* @return true if it the Filter String is contained in a datafield.
|
||||||
|
*/
|
||||||
|
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 MessageType getType() {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return The User who has sent the Message.
|
||||||
|
*/
|
||||||
|
public String getSender() {
|
||||||
|
return sender;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return The Reciever who recieves the Message.
|
||||||
|
*/
|
||||||
|
public String getReceiver() {
|
||||||
|
return receiver;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return The Text of the Message.
|
||||||
|
*/
|
||||||
|
public String getText() {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enummeration of Message Types.
|
||||||
|
*/
|
||||||
|
public enum MessageType {
|
||||||
|
INFO, MESSAGE, ERROR;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
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,11 +1,14 @@
|
|||||||
package ch.zhaw.pm2.multichat.server;
|
package ch.zhaw.pm2.multichat.server;
|
||||||
|
|
||||||
|
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
|
||||||
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.SocketException;
|
import java.net.SocketException;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.locks.Condition;
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
|
|
||||||
public class Server {
|
public class Server {
|
||||||
@@ -62,23 +65,40 @@ public class Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void start() {
|
private void start() {
|
||||||
|
ReentrantLock mutex = new ReentrantLock();
|
||||||
|
Condition nameComplete = mutex.newCondition();
|
||||||
System.out.println("Server started.");
|
System.out.println("Server started.");
|
||||||
try {
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection();
|
NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection();
|
||||||
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections);
|
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections, mutex, nameComplete);
|
||||||
new Thread(connectionHandler).start();
|
new Thread(connectionHandler).start();
|
||||||
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
|
mutex.lock();
|
||||||
connectionHandler.getUserName(),
|
try {
|
||||||
connection.getRemoteHost(),
|
nameComplete.await();
|
||||||
connection.getRemotePort()
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch(SocketException e) {
|
} catch(SocketException e) {
|
||||||
System.out.println("Server connection terminated");
|
System.out.println("Server connection terminated");
|
||||||
}
|
}
|
||||||
catch (IOException e) {
|
catch (IOException e) {
|
||||||
System.err.println("Communication error " + e);
|
System.err.println("Communication error " + e);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
// close server
|
// close server
|
||||||
System.out.println("Server Stopped.");
|
System.out.println("Server Stopped.");
|
||||||
|
|||||||
@@ -1,34 +1,30 @@
|
|||||||
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.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.Condition;
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
|
|
||||||
|
|
||||||
public class ServerConnectionHandler implements Runnable{
|
|
||||||
|
public class ServerConnectionHandler extends ConnectionHandler implements Runnable{
|
||||||
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
|
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
|
||||||
private final int connectionId = connectionCounter.incrementAndGet();
|
private final int connectionId = connectionCounter.incrementAndGet();
|
||||||
private final NetworkHandler.NetworkConnection<String> connection;
|
|
||||||
private final Map<String,ServerConnectionHandler> connectionRegistry;
|
private final Map<String,ServerConnectionHandler> connectionRegistry;
|
||||||
|
|
||||||
// Data types used for the Chat Protocol
|
private ReentrantLock mutex;
|
||||||
private static final String DATA_TYPE_CONNECT = "CONNECT";
|
|
||||||
private static final String DATA_TYPE_CONFIRM = "CONFIRM";
|
|
||||||
private static final String DATA_TYPE_DISCONNECT = "DISCONNECT";
|
|
||||||
private static final String DATA_TYPE_MESSAGE = "MESSAGE";
|
|
||||||
private static final String DATA_TYPE_ERROR = "ERROR";
|
|
||||||
|
|
||||||
private static final String USER_NONE = "";
|
private Condition nameComplete;
|
||||||
private static final String USER_ALL = "*";
|
|
||||||
|
|
||||||
private String userName = "Anonymous-"+connectionId;
|
private String userName = "Anonymous-"+connectionId;
|
||||||
private State state = NEW;
|
private State state = NEW;
|
||||||
@@ -38,150 +34,150 @@ public class ServerConnectionHandler implements Runnable{
|
|||||||
startReceiving();
|
startReceiving();
|
||||||
}
|
}
|
||||||
|
|
||||||
enum State {
|
|
||||||
NEW, CONNECTED, DISCONNECTED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
||||||
Map<String,ServerConnectionHandler> registry) {
|
Map<String,ServerConnectionHandler> registry, ReentrantLock mutex, Condition nameComplete) {
|
||||||
|
super();
|
||||||
|
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;
|
||||||
|
this.mutex = mutex;
|
||||||
|
this.nameComplete = nameComplete;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getUserName() {
|
public String getUserName() {
|
||||||
return this.userName;
|
return this.userName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void startReceiving() {
|
public State getState() {
|
||||||
System.out.println("Starting Connection Handler for " + userName);
|
return state;
|
||||||
try {
|
|
||||||
System.out.println("Start receiving data...");
|
|
||||||
while (connection.isAvailable()) {
|
|
||||||
String data = connection.receive();
|
|
||||||
processData(data);
|
|
||||||
}
|
|
||||||
System.out.println("Stopped recieving data");
|
|
||||||
} catch (SocketException e) {
|
|
||||||
System.out.println("Connection terminated locally");
|
|
||||||
connectionRegistry.remove(userName);
|
|
||||||
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
|
|
||||||
} catch (EOFException e) {
|
|
||||||
System.out.println("Connection terminated by remote");
|
|
||||||
connectionRegistry.remove(userName);
|
|
||||||
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
|
|
||||||
} catch(IOException e) {
|
|
||||||
System.err.println("Communication error: " + e);
|
|
||||||
} catch(ClassNotFoundException e) {
|
|
||||||
System.err.println("Received object of unknown type: " + e.getMessage());
|
|
||||||
}
|
|
||||||
System.out.println("Stopping Connection Handler for " + userName);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stopReceiving() {
|
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());
|
||||||
|
}
|
||||||
|
if (state == ERROR) {
|
||||||
|
System.out.println("Stopping Connection Handler for Rejected Client");
|
||||||
|
} else {
|
||||||
|
System.out.println("Stopping Connection Handler for " + userName);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
private void processData(String data) {
|
||||||
try {
|
try {
|
||||||
// parse data content
|
|
||||||
Scanner scanner = new Scanner(data);
|
Scanner scanner = new Scanner(data);
|
||||||
String sender = null;
|
StringBuilder sender = new StringBuilder();
|
||||||
String reciever = null;
|
StringBuilder reciever = new StringBuilder();
|
||||||
String type = null;
|
StringBuilder type = new StringBuilder();
|
||||||
String payload = null;
|
StringBuilder payload = new StringBuilder();
|
||||||
if (scanner.hasNextLine()) {
|
super.processData(scanner,sender,reciever,type,payload);
|
||||||
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 (type.toString().equals(getDataTypeConnect())) {
|
||||||
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
|
caseConnect(sender.toString());
|
||||||
if (sender == null || sender.isBlank()) sender = this.userName;
|
} else if (type.toString().equals(getDataTypeConfirm())) {
|
||||||
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");
|
System.out.println("Not expecting to receive a CONFIRM request from client");
|
||||||
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
|
} else if (type.toString().equals(getDataTypeDisconnect())) {
|
||||||
if (state == DISCONNECTED)
|
caseDisconnect();
|
||||||
throw new ChatProtocolException("Illegal state for disconnect request: " + state);
|
} else if (type.toString().equals(getDataTypeMessage())) {
|
||||||
if (state == CONNECTED) {
|
caseMessage(sender.toString(), reciever.toString(), type.toString(), payload.toString());
|
||||||
connectionRegistry.remove(this.userName);
|
} else if (type.toString().equals(getDataTypeError())) {
|
||||||
}
|
|
||||||
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);
|
System.err.println("Received error from client (" + sender + "): " + payload);
|
||||||
} else {
|
} else {
|
||||||
System.err.println("Unknown data type received: " + type);
|
System.err.println("Unknown data type received: " + type);
|
||||||
|
|
||||||
}
|
}
|
||||||
} catch(ChatProtocolException e) {
|
} catch(ChatProtocolException e) {
|
||||||
System.out.println("Error while processing data" + e.getMessage());
|
System.out.println("Error while processing data " + e.getMessage());
|
||||||
sendData(USER_NONE, userName, DATA_TYPE_ERROR, e.getMessage());
|
sendData(USER_NONE, userName, getDataTypeError(), e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void sendData(String sender, String receiver, String type, String payload) {
|
private void caseConnect(String sender) throws ChatProtocolException {
|
||||||
if (connection.isAvailable()) {
|
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
|
||||||
new StringBuilder();
|
if (sender.isBlank()) sender = this.userName;
|
||||||
String data = new StringBuilder()
|
if (connectionRegistry.containsKey(sender)) {
|
||||||
.append(sender+"\n")
|
mutex.lock();
|
||||||
.append(receiver+"\n")
|
|
||||||
.append(type+"\n")
|
|
||||||
.append(payload+"\n")
|
|
||||||
.toString();
|
|
||||||
try {
|
try {
|
||||||
connection.send(data);
|
state = ERROR;
|
||||||
} catch (SocketException e) {
|
nameComplete.signal();
|
||||||
System.out.println("Connection closed: " + e.getMessage());
|
}
|
||||||
} catch (EOFException e) {
|
finally {
|
||||||
System.out.println("Connection terminated by remote");
|
mutex.unlock();
|
||||||
} catch(IOException e) {
|
}
|
||||||
System.out.println("Communication error: " + e.getMessage());
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user