Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e53a751081 | ||
|
|
64a6137372 | ||
|
|
5257195d82 | ||
|
|
73dcfb5058 | ||
|
|
84e59effec | ||
|
|
9a534b2465 | ||
|
|
37045ade15 | ||
|
|
313a4f5861 | ||
|
|
2b70299507 | ||
|
|
2b01e92e8d | ||
|
|
a75d3466ef | ||
|
|
97b6fff82e | ||
|
|
2a8b701f48 | ||
|
|
86aa801b34 | ||
|
|
2277fee73a | ||
|
|
d8dbd93c15 | ||
|
|
6e8e560d73 | ||
|
|
5a26c6b127 | ||
|
|
615b3844e3 | ||
|
|
5e6e9d5817 | ||
|
|
4a998b0f61 | ||
|
|
af46e499ff | ||
|
|
8c588ee75c | ||
|
|
800528cc37 | ||
|
|
886d9e5e43 |
@@ -1,8 +1,7 @@
|
|||||||
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.NetworkHandler;
|
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
import javafx.beans.value.ChangeListener;
|
import javafx.beans.value.ChangeListener;
|
||||||
import javafx.beans.value.ObservableValue;
|
import javafx.beans.value.ObservableValue;
|
||||||
@@ -15,10 +14,8 @@ import javafx.scene.layout.Pane;
|
|||||||
import javafx.stage.WindowEvent;
|
import javafx.stage.WindowEvent;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.regex.Matcher;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
|
|
||||||
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
|
||||||
|
|
||||||
public class ChatWindowController {
|
public class ChatWindowController {
|
||||||
private ClientConnectionHandler connectionHandler;
|
private ClientConnectionHandler connectionHandler;
|
||||||
@@ -37,19 +34,20 @@ public class ChatWindowController {
|
|||||||
@FXML private TextField filterValue;
|
@FXML private TextField filterValue;
|
||||||
|
|
||||||
|
|
||||||
@FXML
|
|
||||||
public void initialize() {
|
|
||||||
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
|
|
||||||
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMessages(ClientMessageList messages) {
|
public void setMessages(ClientMessageList messages) {
|
||||||
this.messages = messages;
|
this.messages = messages;
|
||||||
messageListener();
|
messageListener();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setConnectionHandler(ClientConnectionHandler connectionHandler){
|
||||||
|
this.connectionHandler = connectionHandler;
|
||||||
|
startConnectionHandlerListener();
|
||||||
|
serverAddressField.setText(connectionHandler.getServerAddressProperty().get());
|
||||||
|
serverPortField.setText(String.valueOf(connectionHandler.getServerPortProperty().get()));
|
||||||
|
}
|
||||||
|
|
||||||
private void applicationClose() {
|
private void applicationClose() {
|
||||||
connectionHandler.setState(DISCONNECTED);
|
disconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@FXML
|
@FXML
|
||||||
@@ -101,7 +99,7 @@ public class ChatWindowController {
|
|||||||
|
|
||||||
@FXML
|
@FXML
|
||||||
private void applyFilter( ) {
|
private void applyFilter( ) {
|
||||||
this.redrawMessageList();
|
Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void startConnectionHandler() throws IOException {
|
private void startConnectionHandler() throws IOException {
|
||||||
@@ -109,13 +107,11 @@ public class ChatWindowController {
|
|||||||
if(!userName.contains(" ")) {
|
if(!userName.contains(" ")) {
|
||||||
String serverAddress = serverAddressField.getText();
|
String serverAddress = serverAddressField.getText();
|
||||||
int serverPort = Integer.parseInt(serverPortField.getText());
|
int serverPort = Integer.parseInt(serverPortField.getText());
|
||||||
connectionHandler = new ClientConnectionHandler(
|
connectionHandler.initialize(serverAddress, serverPort, userName);
|
||||||
NetworkHandler.openConnection(serverAddress, serverPort), userName,
|
|
||||||
messages);
|
|
||||||
new Thread(connectionHandler).start();
|
new Thread(connectionHandler).start();
|
||||||
|
|
||||||
//register Listener
|
//register Listener
|
||||||
startListener();
|
//startConnectionHandlerListener();
|
||||||
|
|
||||||
// register window close handler
|
// register window close handler
|
||||||
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
||||||
@@ -124,15 +120,6 @@ public class ChatWindowController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void terminateConnectionHandler() {
|
|
||||||
// unregister window close handler
|
|
||||||
rootPane.getScene().getWindow().removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
|
||||||
if (connectionHandler != null) {
|
|
||||||
connectionHandler.stopReceiving();
|
|
||||||
connectionHandler = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stateChanged(State newState) {
|
public void stateChanged(State newState) {
|
||||||
// update UI (need to be run in UI thread: see Platform.runLater())
|
// update UI (need to be run in UI thread: see Platform.runLater())
|
||||||
Platform.runLater(new Runnable() {
|
Platform.runLater(new Runnable() {
|
||||||
@@ -141,8 +128,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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,19 +164,13 @@ public class ChatWindowController {
|
|||||||
messages.addMessage(new Message(Message.MessageType.ERROR, null, null, message));
|
messages.addMessage(new Message(Message.MessageType.ERROR, null, null, message));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void redrawMessageList() {
|
|
||||||
this.messageArea.clear();
|
|
||||||
Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
|
|
||||||
}
|
|
||||||
|
|
||||||
class WindowCloseHandler implements EventHandler<WindowEvent> {
|
class WindowCloseHandler implements EventHandler<WindowEvent> {
|
||||||
public void handle(WindowEvent event) {
|
public void handle(WindowEvent event) {
|
||||||
applicationClose();
|
applicationClose();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void startListener() {
|
public void startConnectionHandlerListener() {
|
||||||
connectionHandler.getStateProperty().addListener(new ChangeListener<State>() {
|
connectionHandler.getStateProperty().addListener(new ChangeListener<State>() {
|
||||||
@Override
|
@Override
|
||||||
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
|
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
|
||||||
@@ -223,7 +204,7 @@ public class ChatWindowController {
|
|||||||
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
|
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
|
||||||
@Override
|
@Override
|
||||||
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
|
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
|
||||||
redrawMessageList();
|
Platform.runLater(() -> messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
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.SimpleIntegerProperty;
|
||||||
import javafx.beans.property.SimpleObjectProperty;
|
import javafx.beans.property.SimpleObjectProperty;
|
||||||
@@ -12,21 +13,9 @@ import java.net.SocketException;
|
|||||||
import java.util.Scanner;
|
import java.util.Scanner;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
|
||||||
|
|
||||||
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
|
||||||
|
|
||||||
public class ClientConnectionHandler implements Runnable {
|
|
||||||
private final 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 final Pattern messagePattern = Pattern.compile( "^(?:@(\\S*))?\\s*(.*)$" );
|
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\S*))?\\s*(.*)$" );
|
||||||
|
|
||||||
@@ -36,19 +25,21 @@ public class ClientConnectionHandler implements Runnable {
|
|||||||
private SimpleStringProperty serverAddress;
|
private SimpleStringProperty serverAddress;
|
||||||
private SimpleIntegerProperty serverPort;
|
private SimpleIntegerProperty serverPort;
|
||||||
|
|
||||||
enum State {
|
public ClientConnectionHandler(ClientMessageList messages) {
|
||||||
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
|
super();
|
||||||
|
this.messages = messages;
|
||||||
|
state = new SimpleObjectProperty<>(State.NEW);
|
||||||
|
serverAddress = new SimpleStringProperty(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
|
||||||
|
serverPort = new SimpleIntegerProperty(NetworkHandler.DEFAULT_PORT);
|
||||||
|
this.userName = new SimpleStringProperty(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
public void initialize(String serverAddress, int serverPort, String userName) throws IOException {
|
||||||
String userName,
|
state.set(NEW);
|
||||||
ClientMessageList messages) {
|
this.serverAddress.set(serverAddress);
|
||||||
this.connection = connection;
|
this.serverPort.set(serverPort);
|
||||||
this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName);
|
setConnection(NetworkHandler.openConnection(serverAddress, serverPort));
|
||||||
this.messages = messages;
|
this.userName.set((userName == null || userName.isBlank())? USER_NONE : userName);
|
||||||
state = new SimpleObjectProperty<>(NEW);
|
|
||||||
serverAddress = new SimpleStringProperty();
|
|
||||||
serverPort = new SimpleIntegerProperty();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public SimpleStringProperty getServerAddressProperty() { return serverAddress; }
|
public SimpleStringProperty getServerAddressProperty() { return serverAddress; }
|
||||||
@@ -69,12 +60,12 @@ public class ClientConnectionHandler implements Runnable {
|
|||||||
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");
|
||||||
@@ -98,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());
|
||||||
@@ -108,38 +99,38 @@ 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())) {
|
||||||
|
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 {
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void caseConfirm(String sender, String reciever, String payload) {
|
||||||
if (state.get() == CONFIRM_CONNECT) {
|
if (state.get() == CONFIRM_CONNECT) {
|
||||||
this.userName.set(reciever);
|
this.userName.set(reciever);
|
||||||
this.serverPort.set(connection.getRemotePort());
|
this.serverPort.set(getConnection().getRemotePort());
|
||||||
this.serverAddress.set(connection.getRemoteHost());
|
this.serverAddress.set(getConnection().getRemoteHost());
|
||||||
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
|
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
|
||||||
System.out.println("CONFIRM: " + payload);
|
System.out.println("CONFIRM: " + payload);
|
||||||
this.setState(CONNECTED);
|
this.setState(CONNECTED);
|
||||||
@@ -150,7 +141,9 @@ public class ClientConnectionHandler implements Runnable {
|
|||||||
} else {
|
} else {
|
||||||
System.err.println("Got unexpected confirm message: " + payload);
|
System.err.println("Got unexpected confirm message: " + payload);
|
||||||
}
|
}
|
||||||
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
|
}
|
||||||
|
|
||||||
|
private void caseDisconnect(String sender, String reciever, String payload) {
|
||||||
if (state.get() == DISCONNECTED) {
|
if (state.get() == DISCONNECTED) {
|
||||||
System.out.println("DISCONNECT: Already in disconnected: " + payload);
|
System.out.println("DISCONNECT: Already in disconnected: " + payload);
|
||||||
return;
|
return;
|
||||||
@@ -158,55 +151,31 @@ public class ClientConnectionHandler implements Runnable {
|
|||||||
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
|
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
|
||||||
System.out.println("DISCONNECT: " + payload);
|
System.out.println("DISCONNECT: " + payload);
|
||||||
this.setState(DISCONNECTED);
|
this.setState(DISCONNECTED);
|
||||||
} else if (type.equals(DATA_TYPE_MESSAGE)) {
|
}
|
||||||
|
|
||||||
|
private void caseMessage(String sender, String reciever, String payload) {
|
||||||
if (state.get() != CONNECTED) {
|
if (state.get() != CONNECTED) {
|
||||||
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
|
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
messages.addMessage(new Message(Message.MessageType.MESSAGE,sender,reciever,payload));
|
messages.addMessage(new Message(Message.MessageType.MESSAGE,sender,reciever,payload));
|
||||||
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
|
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
|
||||||
} else if (type.equals(DATA_TYPE_ERROR)) {
|
|
||||||
messages.addMessage(new Message(Message.MessageType.ERROR,sender,reciever,payload));
|
|
||||||
System.out.println("ERROR: " + payload);
|
|
||||||
} else {
|
|
||||||
System.out.println("Unknown data type received: " + type);
|
|
||||||
}
|
|
||||||
} catch (ChatProtocolException e) {
|
|
||||||
System.err.println("Error while processing data: " + e.getMessage());
|
|
||||||
sendData(USER_NONE, userName.get(), DATA_TYPE_ERROR, e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void sendData(String sender, String receiver, String type, String payload) {
|
private void caseError(String sender, String reciever, String payload) {
|
||||||
if (connection.isAvailable()) {
|
messages.addMessage(new Message(Message.MessageType.ERROR,sender,reciever,payload));
|
||||||
new StringBuilder();
|
System.out.println("ERROR: " + payload);
|
||||||
String data = new StringBuilder()
|
|
||||||
.append(sender+"\n")
|
|
||||||
.append(receiver+"\n")
|
|
||||||
.append(type+"\n")
|
|
||||||
.append(payload+"\n")
|
|
||||||
.toString();
|
|
||||||
try {
|
|
||||||
connection.send(data);
|
|
||||||
} catch (SocketException e) {
|
|
||||||
System.err.println("Connection closed: " + e.getMessage());
|
|
||||||
} catch (EOFException e) {
|
|
||||||
System.out.println("Connection terminated by remote");
|
|
||||||
} catch(IOException e) {
|
|
||||||
System.err.println("Communication error: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void connect() throws ChatProtocolException {
|
public void connect() throws ChatProtocolException {
|
||||||
if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
|
if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
|
||||||
this.sendData(userName.get(), USER_NONE, DATA_TYPE_CONNECT,null);
|
this.sendData(userName.get(), USER_NONE, getDataTypeConnect(),null);
|
||||||
this.setState(CONFIRM_CONNECT);
|
this.setState(CONFIRM_CONNECT);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void disconnect() throws ChatProtocolException {
|
public void disconnect() throws ChatProtocolException {
|
||||||
if (state.get() != NEW && state.get() != 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.get(), USER_NONE, DATA_TYPE_DISCONNECT,null);
|
this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(),null);
|
||||||
this.setState(CONFIRM_DISCONNECT);
|
this.setState(CONFIRM_DISCONNECT);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,11 +190,10 @@ public class ClientConnectionHandler implements Runnable {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
|
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
|
||||||
this.sendData(userName.get(), receiver, DATA_TYPE_MESSAGE,message);
|
this.sendData(userName.get(), receiver, getDataTypeMessage(),message);
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import javafx.stage.Stage;
|
|||||||
|
|
||||||
public class ClientUI extends Application {
|
public class ClientUI extends Application {
|
||||||
private ClientMessageList clientMessageList = new ClientMessageList();
|
private ClientMessageList clientMessageList = new ClientMessageList();
|
||||||
|
private ClientConnectionHandler connectionHandler = new ClientConnectionHandler(clientMessageList);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start(Stage primaryStage) {
|
public void start(Stage primaryStage) {
|
||||||
@@ -21,6 +22,7 @@ public class ClientUI extends Application {
|
|||||||
|
|
||||||
ChatWindowController chatWindowController = loader.getController();
|
ChatWindowController chatWindowController = loader.getController();
|
||||||
chatWindowController.setMessages(clientMessageList);
|
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);
|
||||||
|
|||||||
@@ -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,13 +1,24 @@
|
|||||||
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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This Class represents a Server. The user can start the programm with the port number as a argument.
|
||||||
|
* If no argument has been set the {@link NetworkHandler#DEFAULT_PORT} is used as port number.
|
||||||
|
* After initialising the server:
|
||||||
|
* 1. Starts a Socketserver using the logic given in {@link NetworkHandler.NetworkServer#createServer()}
|
||||||
|
* 2. The server starts to listen for incoming connection using the Logic given in {@link NetworkHandler.NetworkServer#waitForConnection()}
|
||||||
|
* 3. New conections will be atached to a Connectionhandler: {@link ServerConnectionHandler} and placed in a Map containing all active connections {@link Server#connections}
|
||||||
|
*
|
||||||
|
*/
|
||||||
public class Server {
|
public class Server {
|
||||||
|
|
||||||
// Server connection
|
// Server connection
|
||||||
@@ -54,6 +65,11 @@ public class Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Constructor to create a new instance.
|
||||||
|
* @param serverPort to listen for incoming connections.
|
||||||
|
* @throws IOException thrown if an I/O error occurs when opening the socket.
|
||||||
|
*/
|
||||||
public Server(int serverPort) throws IOException {
|
public Server(int serverPort) throws IOException {
|
||||||
// Open server connection
|
// Open server connection
|
||||||
System.out.println("Create server connection");
|
System.out.println("Create server connection");
|
||||||
@@ -61,29 +77,32 @@ public class Server {
|
|||||||
System.out.println("Listening on " + networkServer.getHostAddress() + ":" + networkServer.getHostPort());
|
System.out.println("Listening on " + networkServer.getHostAddress() + ":" + networkServer.getHostPort());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* With this methode the instance waits for incoming connections. If a client tries to connect to the server.
|
||||||
|
* The connection will be registered in the connection registry if successful.
|
||||||
|
*/
|
||||||
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>",
|
|
||||||
connectionHandler.getUserName(),
|
|
||||||
connection.getRemoteHost(),
|
|
||||||
connection.getRemotePort()
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
} catch(SocketException e) {
|
} catch(SocketException e) {
|
||||||
System.out.println("Server connection terminated");
|
System.out.println("Server connection terminated");
|
||||||
}
|
} catch (IOException e) {
|
||||||
catch (IOException e) {
|
|
||||||
System.err.println("Communication error " + e);
|
System.err.println("Communication error " + e);
|
||||||
}
|
}
|
||||||
// close server
|
// close server
|
||||||
System.out.println("Server Stopped.");
|
System.out.println("Server Stopped.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method will stop the serversocket.
|
||||||
|
*/
|
||||||
public void terminate() {
|
public void terminate() {
|
||||||
try {
|
try {
|
||||||
System.out.println("Close server port.");
|
System.out.println("Close server port.");
|
||||||
|
|||||||
@@ -1,65 +1,110 @@
|
|||||||
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{
|
/**
|
||||||
|
* This class represents the connection between the server and a client and offers the serverside logic.
|
||||||
|
* The ServerConnectionHandler receives data send from the client aswell as sends data to the client.
|
||||||
|
*
|
||||||
|
* The ServeConnectionHandler offers following functionality:
|
||||||
|
*
|
||||||
|
* Evaluating connection attempts from a client by:
|
||||||
|
* 1. Checks if Username is valid (Not used)
|
||||||
|
* 2. Saves Username in {@link ServerConnectionHandler#userName}
|
||||||
|
* 3. Saves the connection in the {@link ServerConnectionHandler#connectionRegistry}
|
||||||
|
*
|
||||||
|
* Processes disconnections from a client by:
|
||||||
|
* 1. Removing the connection from the {@link ServerConnectionHandler#connectionRegistry}
|
||||||
|
* 2. Terminates the socket by calling {@link NetworkHandler.NetworkConnection#close()}
|
||||||
|
*
|
||||||
|
* Processes Messages send from a client by:
|
||||||
|
* 1. Evaluating the reciever by differentiating between broadcast or unicast.
|
||||||
|
* 2. Sending the message accordingly.
|
||||||
|
*
|
||||||
|
* To use this class, start a new instance and start it in a thread.
|
||||||
|
* To constructor needs following parameter:
|
||||||
|
* 1. {@link ch.zhaw.pm2.multichat.protocol.NetworkHandler.NetworkConnection} representing the socket connection between server and client
|
||||||
|
* 2. {@link Map<String,ServerConnectionHandler>} registry to check for all active connections
|
||||||
|
* 3. {@link ReentrantLock @link Condition} to lock server thread to evaluate connection.
|
||||||
|
* */
|
||||||
|
public class ServerConnectionHandler extends ConnectionHandler implements Runnable{
|
||||||
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
|
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
|
||||||
private final int connectionId = connectionCounter.incrementAndGet();
|
private final int connectionId = connectionCounter.incrementAndGet();
|
||||||
private final NetworkHandler.NetworkConnection<String> connection;
|
|
||||||
private final Map<String,ServerConnectionHandler> connectionRegistry;
|
private final Map<String,ServerConnectionHandler> connectionRegistry;
|
||||||
|
|
||||||
// Data types used for the Chat Protocol
|
private 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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when runnable gets started in a thread.
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
startReceiving();
|
startReceiving();
|
||||||
}
|
}
|
||||||
|
|
||||||
enum State {
|
/**
|
||||||
NEW, CONNECTED, DISCONNECTED;
|
* Constructor to intitialize the connection
|
||||||
}
|
* @param connection representing the socket connection between server and clinet
|
||||||
|
* @param registry map containing all active connections between server and clients
|
||||||
|
* @param mutex to lock thread
|
||||||
|
* @param nameComplete condition to call threads
|
||||||
|
*/
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @return the username of the connected client
|
||||||
|
*/
|
||||||
public String getUserName() {
|
public String getUserName() {
|
||||||
return this.userName;
|
return this.userName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void startReceiving() {
|
/**
|
||||||
|
*
|
||||||
|
* @return state of the connection. Poosible states are see {@link ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State}
|
||||||
|
*/
|
||||||
|
public State getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This methods runs in a whileloop as long as the socket between server and client is available
|
||||||
|
* and the connection State is not ERROR.
|
||||||
|
*/
|
||||||
|
private void startReceiving() {
|
||||||
System.out.println("Starting Connection Handler for new User");
|
System.out.println("Starting Connection Handler for new User");
|
||||||
try {
|
try {
|
||||||
System.out.println("Start receiving data...");
|
System.out.println("Start receiving data...");
|
||||||
while (connection.isAvailable()) {
|
while (getConnection().isAvailable() && !(state == ERROR)) {
|
||||||
String data = connection.receive();
|
String data = getConnection().receive();
|
||||||
processData(data);
|
processData(data);
|
||||||
}
|
}
|
||||||
System.out.println("Stopped recieving data");
|
System.out.println("Stopped recieving data");
|
||||||
@@ -71,75 +116,129 @@ public class ServerConnectionHandler implements Runnable{
|
|||||||
System.out.println("Connection terminated by remote");
|
System.out.println("Connection terminated by remote");
|
||||||
connectionRegistry.remove(userName);
|
connectionRegistry.remove(userName);
|
||||||
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
|
System.out.println("Unregistered because client connection terminated: " + userName + " " + e.getMessage());
|
||||||
} catch(IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("Communication error: " + e);
|
System.err.println("Communication error: " + e);
|
||||||
} catch(ClassNotFoundException e) {
|
} catch (ClassNotFoundException e) {
|
||||||
System.err.println("Received object of unknown type: " + e.getMessage());
|
System.err.println("Received object of unknown type: " + e.getMessage());
|
||||||
}
|
}
|
||||||
|
if (state == ERROR) {
|
||||||
|
System.out.println("Stopping Connection Handler for Rejected Client");
|
||||||
|
} else {
|
||||||
System.out.println("Stopping Connection Handler for " + userName);
|
System.out.println("Stopping Connection Handler for " + userName);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stopReceiving() {
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method will call {@link NetworkHandler.NetworkConnection#close()} to close the Socket.
|
||||||
|
*/
|
||||||
|
private void stopReceiving() {
|
||||||
System.out.println("Closing Connection Handler for " + userName);
|
System.out.println("Closing Connection Handler for " + userName);
|
||||||
try {
|
try {
|
||||||
System.out.println("Stop receiving data...");
|
System.out.println("Stop receiving data...");
|
||||||
connection.close();
|
getConnection().close();
|
||||||
System.out.println("Stopped receiving data.");
|
System.out.println("Stopped receiving data.");
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("Failed to close connection." + e);
|
System.err.println("Failed to close connection." + e.getMessage());
|
||||||
}
|
}
|
||||||
System.out.println("Closed Connection Handler for " + userName);
|
System.out.println("Closed Connection Handler for " + userName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method gets called when socket recieves data. The method checks for the data type and reacts accordingly
|
||||||
|
* If data type:
|
||||||
|
* 1. Connect => checks if username is valid. if valid sends response to client with confirmation.
|
||||||
|
* If username not valid quits connection by changing status to ERROR.
|
||||||
|
* 2. Confirm => Server should not recieve this kind of message. STDOUT informs about it.
|
||||||
|
* 3. Disconnect => Disconnects connection by removing connection from registry and calling method to terminate socket.
|
||||||
|
* 4. Message => Checks if broadcast or unicast. Sends data accordingly
|
||||||
|
* 5. Error => STDERR message
|
||||||
|
* @param data recieved by the server
|
||||||
|
*/
|
||||||
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())) {
|
||||||
|
caseConnect(sender.toString());
|
||||||
|
} else if (type.toString().equals(getDataTypeConfirm())) {
|
||||||
|
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())) {
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is called by method {@link ServerConnectionHandler#processData(String)}
|
||||||
|
* Checks if username is valid. if valid sends response to client with confirmation.
|
||||||
|
* @param sender of the payload
|
||||||
|
* @throws ChatProtocolException if username not valid
|
||||||
|
*/
|
||||||
|
private void caseConnect(String sender) throws ChatProtocolException {
|
||||||
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
|
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
|
||||||
if (sender == null || sender.isBlank()) sender = this.userName;
|
if (sender.isBlank()) sender = this.userName;
|
||||||
if (connectionRegistry.containsKey(sender))
|
//if username not valid
|
||||||
|
if (connectionRegistry.containsKey(sender)) {
|
||||||
|
state = ERROR;
|
||||||
|
System.out.println(String.format("Connecting failed for new Client with IP:Port <%s:%d>.\nReason: Name already taken.",
|
||||||
|
getConnection().getRemoteHost(),
|
||||||
|
getConnection().getRemotePort()));
|
||||||
throw new ChatProtocolException("User name already taken: " + sender);
|
throw new ChatProtocolException("User name already taken: " + sender);
|
||||||
|
}
|
||||||
|
//if username valid
|
||||||
this.userName = sender;
|
this.userName = sender;
|
||||||
connectionRegistry.put(userName, this);
|
connectionRegistry.put(userName, this);
|
||||||
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Registration successfull for " + userName);
|
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
|
||||||
this.state = CONNECTED;
|
this.state = CONNECTED;
|
||||||
} else if (type.equals(DATA_TYPE_CONFIRM)) {
|
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
|
||||||
System.out.println("Not expecting to receive a CONFIRM request from client");
|
userName,
|
||||||
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
|
getConnection().getRemoteHost(),
|
||||||
|
getConnection().getRemotePort()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is called by method {@link ServerConnectionHandler#processData(String)}
|
||||||
|
* Disconnects connection by removing connection from registry and calling method {@link ServerConnectionHandler#stopReceiving()} to terminate socket.
|
||||||
|
* @throws ChatProtocolException if state allready DISCONNECTED.
|
||||||
|
*/
|
||||||
|
private void caseDisconnect() throws ChatProtocolException {
|
||||||
if (state == DISCONNECTED)
|
if (state == DISCONNECTED)
|
||||||
throw new ChatProtocolException("Illegal state for disconnect request: " + state);
|
throw new ChatProtocolException("Illegal state for disconnect request: " + state);
|
||||||
if (state == CONNECTED) {
|
if (state == CONNECTED) {
|
||||||
connectionRegistry.remove(this.userName);
|
connectionRegistry.remove(this.userName);
|
||||||
}
|
}
|
||||||
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Confirm disconnect of " + userName);
|
sendData(USER_NONE, userName, getDataTypeConfirm(), "Confirm disconnect of " + userName);
|
||||||
this.state = DISCONNECTED;
|
this.state = DISCONNECTED;
|
||||||
this.stopReceiving();
|
this.stopReceiving();
|
||||||
} else if (type.equals(DATA_TYPE_MESSAGE)) {
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is called by method {@link ServerConnectionHandler#processData(String)}
|
||||||
|
* Checks if broadcast or unicast. Sends data accordingly
|
||||||
|
* @param sender who sent data
|
||||||
|
* @param reciever to recieve data
|
||||||
|
* @param type of message
|
||||||
|
* @param payload data to transmit
|
||||||
|
* @throws ChatProtocolException if state not equal to CONNECT
|
||||||
|
*/
|
||||||
|
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 (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state);
|
||||||
if (USER_ALL.equals(reciever)) {
|
if (USER_ALL.equals(reciever)) {
|
||||||
for (ServerConnectionHandler handler : connectionRegistry.values()) {
|
for (ServerConnectionHandler handler : connectionRegistry.values()) {
|
||||||
@@ -153,38 +252,7 @@ public class ServerConnectionHandler implements Runnable{
|
|||||||
sendData(sender, reciever, type, payload); //send message to sender if it's a direct message and sender is not receiver.
|
sendData(sender, reciever, type, payload); //send message to sender if it's a direct message and sender is not receiver.
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this.sendData(USER_NONE, userName, DATA_TYPE_ERROR, "Unknown User: " + reciever);
|
this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + reciever);
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (type.equals(DATA_TYPE_ERROR)) {
|
|
||||||
System.err.println("Received error from client (" + sender + "): " + payload);
|
|
||||||
} else {
|
|
||||||
System.err.println("Unknown data type received: " + type);
|
|
||||||
|
|
||||||
}
|
|
||||||
} catch(ChatProtocolException e) {
|
|
||||||
System.out.println("Error while processing data" + e.getMessage());
|
|
||||||
sendData(USER_NONE, userName, DATA_TYPE_ERROR, e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void sendData(String sender, String receiver, String type, String payload) {
|
|
||||||
if (connection.isAvailable()) {
|
|
||||||
new StringBuilder();
|
|
||||||
String data = new StringBuilder()
|
|
||||||
.append(sender+"\n")
|
|
||||||
.append(receiver+"\n")
|
|
||||||
.append(type+"\n")
|
|
||||||
.append(payload+"\n")
|
|
||||||
.toString();
|
|
||||||
try {
|
|
||||||
connection.send(data);
|
|
||||||
} catch (SocketException e) {
|
|
||||||
System.out.println("Connection closed: " + e.getMessage());
|
|
||||||
} catch (EOFException e) {
|
|
||||||
System.out.println("Connection terminated by remote");
|
|
||||||
} catch(IOException e) {
|
|
||||||
System.out.println("Communication error: " + e.getMessage());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user