Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c588ee75c | ||
|
|
800528cc37 | ||
|
|
886d9e5e43 | ||
|
|
7c68472859 | ||
|
|
b9ffb2b133 | ||
|
|
e69ced4081 | ||
|
|
d1dfe6c1ab | ||
|
|
3eedf58685 | ||
|
|
1777b62582 | ||
|
|
a0b7b363c3 | ||
|
|
914fa8f1e2 | ||
|
|
9eb352c0fe | ||
|
|
a27b7f4446 | ||
|
|
1a188f6bbd | ||
|
|
56200b749d | ||
|
|
7e7333dfaf | ||
|
|
3082da8a91 | ||
|
|
424a174847 | ||
|
|
b246c3c7e3 | ||
|
|
eb0e6d0dbc | ||
|
|
0896257fad | ||
|
|
e11fb136cf |
@@ -4,6 +4,8 @@ import ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State;
|
||||
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
||||
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||
import javafx.application.Platform;
|
||||
import javafx.beans.value.ChangeListener;
|
||||
import javafx.beans.value.ObservableValue;
|
||||
import javafx.event.EventHandler;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.control.Button;
|
||||
@@ -19,7 +21,6 @@ import java.util.regex.Pattern;
|
||||
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
||||
|
||||
public class ChatWindowController {
|
||||
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
|
||||
private ClientConnectionHandler connectionHandler;
|
||||
private ClientMessageList messages;
|
||||
|
||||
@@ -40,17 +41,20 @@ public class ChatWindowController {
|
||||
public void initialize() {
|
||||
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
|
||||
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT));
|
||||
stateChanged(NEW);
|
||||
messages = new ClientMessageList(this);
|
||||
}
|
||||
|
||||
public void setMessages(ClientMessageList messages) {
|
||||
this.messages = messages;
|
||||
messageListener();
|
||||
}
|
||||
|
||||
private void applicationClose() {
|
||||
connectionHandler.setState(DISCONNECTED);
|
||||
disconnect();
|
||||
}
|
||||
|
||||
@FXML
|
||||
private void toggleConnection () {
|
||||
if (connectionHandler == null || connectionHandler.getState() != CONNECTED) {
|
||||
if (connectionHandler == null || connectionHandler.getStateProperty().get() != CONNECTED) {
|
||||
connect();
|
||||
} else {
|
||||
disconnect();
|
||||
@@ -59,46 +63,39 @@ public class ChatWindowController {
|
||||
|
||||
private void connect() {
|
||||
try {
|
||||
messages = new ClientMessageList(this); // clear message list
|
||||
messages.clear(); // clear message list
|
||||
startConnectionHandler();
|
||||
connectionHandler.connect();
|
||||
} catch(ChatProtocolException | IOException e) {
|
||||
writeError(e.getMessage());
|
||||
addError(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void disconnect() {
|
||||
if (connectionHandler == null) {
|
||||
writeError("No connection handler");
|
||||
addError("No connection handler");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
connectionHandler.disconnect();
|
||||
} catch (ChatProtocolException e) {
|
||||
writeError(e.getMessage());
|
||||
addError(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@FXML
|
||||
private void message() {
|
||||
if (connectionHandler == null) {
|
||||
writeError("No connection handler");
|
||||
return;
|
||||
}
|
||||
String messageString = messageField.getText().strip();
|
||||
messageField.clear();
|
||||
Matcher matcher = messagePattern.matcher(messageString);
|
||||
if (matcher.find()) {
|
||||
String receiver = matcher.group(1);
|
||||
String message = matcher.group(2);
|
||||
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
|
||||
try {
|
||||
connectionHandler.message(receiver, message);
|
||||
} catch (ChatProtocolException e) {
|
||||
writeError(e.getMessage());
|
||||
try {
|
||||
if (connectionHandler == null) {
|
||||
addError("No connection handler");
|
||||
} else if (!connectionHandler.message(messageString)) {
|
||||
addError("Not a valid message format.");
|
||||
} else {
|
||||
messageField.clear();
|
||||
}
|
||||
} else {
|
||||
writeError("Not a valid message format.");
|
||||
} catch (ChatProtocolException e) {
|
||||
addError(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,9 +110,12 @@ public class ChatWindowController {
|
||||
int serverPort = Integer.parseInt(serverPortField.getText());
|
||||
connectionHandler = new ClientConnectionHandler(
|
||||
NetworkHandler.openConnection(serverAddress, serverPort), userName,
|
||||
this);
|
||||
messages);
|
||||
new Thread(connectionHandler).start();
|
||||
|
||||
//register Listener
|
||||
startListener();
|
||||
|
||||
// register window close handler
|
||||
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
||||
}
|
||||
@@ -169,43 +169,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) {
|
||||
messages.addMessage(ClientMessageList.MessageType.ERROR, null, null, message);
|
||||
this.redrawMessageList();
|
||||
messages.addMessage(new Message(Message.MessageType.ERROR, null, null, message));
|
||||
}
|
||||
|
||||
public void clearMessageArea() {
|
||||
this.messageArea.clear();
|
||||
}
|
||||
|
||||
|
||||
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> {
|
||||
public void handle(WindowEvent event) {
|
||||
applicationClose();
|
||||
@@ -213,7 +185,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();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,17 +2,21 @@ package ch.zhaw.pm2.multichat.client;
|
||||
|
||||
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
||||
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.IOException;
|
||||
import java.net.SocketException;
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
||||
|
||||
public class ClientConnectionHandler implements Runnable {
|
||||
private final NetworkHandler.NetworkConnection<String> connection;
|
||||
private final ChatWindowController controller;
|
||||
|
||||
// Data types used for the Chat Protocol
|
||||
private static final String DATA_TYPE_CONNECT = "CONNECT";
|
||||
@@ -24,8 +28,13 @@ public class ClientConnectionHandler implements Runnable {
|
||||
public static final String USER_NONE = "";
|
||||
public static final String USER_ALL = "*";
|
||||
|
||||
private String userName = USER_NONE;
|
||||
private State state = NEW;
|
||||
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
|
||||
|
||||
private SimpleStringProperty userName;
|
||||
private SimpleObjectProperty<State> state;
|
||||
private ClientMessageList messages;
|
||||
private SimpleStringProperty serverAddress;
|
||||
private SimpleIntegerProperty serverPort;
|
||||
|
||||
enum State {
|
||||
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
|
||||
@@ -33,19 +42,28 @@ public class ClientConnectionHandler implements Runnable {
|
||||
|
||||
public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
||||
String userName,
|
||||
ChatWindowController controller) {
|
||||
ClientMessageList messages) {
|
||||
this.connection = connection;
|
||||
this.userName = (userName == null || userName.isBlank())? USER_NONE : userName;
|
||||
this.controller = controller;
|
||||
this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName);
|
||||
this.messages = messages;
|
||||
state = new SimpleObjectProperty<>(NEW);
|
||||
serverAddress = new SimpleStringProperty();
|
||||
serverPort = new SimpleIntegerProperty();
|
||||
}
|
||||
|
||||
public State getState() {
|
||||
public SimpleStringProperty getServerAddressProperty() { return serverAddress; }
|
||||
|
||||
public SimpleIntegerProperty getServerPortProperty() { return serverPort; }
|
||||
|
||||
public SimpleObjectProperty<State> getStateProperty() {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
public SimpleStringProperty getUserNameProperty() { return userName; }
|
||||
|
||||
public void setState (State newState) {
|
||||
this.state = newState;
|
||||
controller.stateChanged(newState);
|
||||
state.set(newState);
|
||||
|
||||
}
|
||||
|
||||
public void run () {
|
||||
@@ -119,45 +137,44 @@ public class ClientConnectionHandler implements Runnable {
|
||||
if (type.equals(DATA_TYPE_CONNECT)) {
|
||||
System.err.println("Illegal connect request from server");
|
||||
} else if (type.equals(DATA_TYPE_CONFIRM)) {
|
||||
if (state == CONFIRM_CONNECT) {
|
||||
this.userName = reciever;
|
||||
controller.setUserName(userName);
|
||||
controller.setServerPort(connection.getRemotePort());
|
||||
controller.setServerAddress(connection.getRemoteHost());
|
||||
controller.addInfo(payload);
|
||||
if (state.get() == CONFIRM_CONNECT) {
|
||||
this.userName.set(reciever);
|
||||
this.serverPort.set(connection.getRemotePort());
|
||||
this.serverAddress.set(connection.getRemoteHost());
|
||||
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
|
||||
System.out.println("CONFIRM: " + payload);
|
||||
this.setState(CONNECTED);
|
||||
} else if (state == CONFIRM_DISCONNECT) {
|
||||
controller.addInfo(payload);
|
||||
} else if (state.get() == CONFIRM_DISCONNECT) {
|
||||
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
|
||||
System.out.println("CONFIRM: " + payload);
|
||||
this.setState(DISCONNECTED);
|
||||
} else {
|
||||
System.err.println("Got unexpected confirm message: " + payload);
|
||||
}
|
||||
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
|
||||
if (state == DISCONNECTED) {
|
||||
if (state.get() == DISCONNECTED) {
|
||||
System.out.println("DISCONNECT: Already in disconnected: " + payload);
|
||||
return;
|
||||
}
|
||||
controller.addInfo(payload);
|
||||
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
|
||||
System.out.println("DISCONNECT: " + payload);
|
||||
this.setState(DISCONNECTED);
|
||||
} else if (type.equals(DATA_TYPE_MESSAGE)) {
|
||||
if (state != CONNECTED) {
|
||||
if (state.get() != CONNECTED) {
|
||||
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
|
||||
return;
|
||||
}
|
||||
controller.addMessage(sender, reciever, payload);
|
||||
messages.addMessage(new Message(Message.MessageType.MESSAGE,sender,reciever,payload));
|
||||
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
|
||||
} else if (type.equals(DATA_TYPE_ERROR)) {
|
||||
controller.addError(payload);
|
||||
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, DATA_TYPE_ERROR, e.getMessage());
|
||||
sendData(USER_NONE, userName.get(), DATA_TYPE_ERROR, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,20 +200,33 @@ public class ClientConnectionHandler implements Runnable {
|
||||
}
|
||||
|
||||
public void connect() throws ChatProtocolException {
|
||||
if (state != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
|
||||
this.sendData(userName, USER_NONE, DATA_TYPE_CONNECT,null);
|
||||
if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
|
||||
this.sendData(userName.get(), USER_NONE, DATA_TYPE_CONNECT,null);
|
||||
this.setState(CONFIRM_CONNECT);
|
||||
}
|
||||
|
||||
public void disconnect() throws ChatProtocolException {
|
||||
if (state != NEW && state != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + state);
|
||||
this.sendData(userName, USER_NONE, DATA_TYPE_DISCONNECT,null);
|
||||
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.setState(CONFIRM_DISCONNECT);
|
||||
}
|
||||
|
||||
public void message(String receiver, String message) throws ChatProtocolException {
|
||||
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state);
|
||||
this.sendData(userName, receiver, DATA_TYPE_MESSAGE,message);
|
||||
public boolean message(String messageString) throws ChatProtocolException {
|
||||
if (state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state);
|
||||
|
||||
Matcher matcher = messagePattern.matcher(messageString);
|
||||
if (matcher.find()) {
|
||||
String receiver = matcher.group(1);
|
||||
String message = matcher.group(2);
|
||||
if(message.length() < 1){
|
||||
return false;
|
||||
}
|
||||
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
|
||||
this.sendData(userName.get(), receiver, DATA_TYPE_MESSAGE,message);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,51 +1,41 @@
|
||||
package ch.zhaw.pm2.multichat.client;
|
||||
|
||||
import javafx.beans.property.SimpleBooleanProperty;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class ClientMessageList {
|
||||
private final List<MessageType> typeList = new ArrayList<>();
|
||||
private final List<String> senderList = new ArrayList<>();
|
||||
private final List<String> receiverList = new ArrayList<>();
|
||||
private final List<String> messageList = new ArrayList<>();
|
||||
private final ChatWindowController gui;
|
||||
private List<Message> messages = new ArrayList<>();
|
||||
private SimpleBooleanProperty changed = new SimpleBooleanProperty(false);
|
||||
|
||||
public ClientMessageList(ChatWindowController gui) {
|
||||
this.gui = gui;
|
||||
}
|
||||
|
||||
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 addMessage(Message message) {
|
||||
messages.add(message);
|
||||
changed.set(!changed.get());
|
||||
}
|
||||
|
||||
public void writeFilteredMessages(String filter) {
|
||||
public String getFilteredMessages(String filter) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
boolean showAll = filter == null || filter.isBlank();
|
||||
gui.clearMessageArea();
|
||||
for(int i=0; i<senderList.size(); i++) {
|
||||
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))
|
||||
for(Message message : messages) {
|
||||
if(showAll || message.matchesFilter(filter))
|
||||
{
|
||||
switch (typeList.get(i)) {
|
||||
case MESSAGE: gui.writeMessage(senderList.get(i), receiverList.get(i), messageList.get(i)); break;
|
||||
case ERROR: gui.writeError(messageList.get(i)); break;
|
||||
case INFO: gui.writeInfo(messageList.get(i)); break;
|
||||
default: gui.writeError("Unexpected message type: " + typeList.get(i));
|
||||
switch (message.getType()) {
|
||||
case MESSAGE -> result.append(String.format("[%s -> %s] %s\n", message.getSender(), message.getReceiver(), message.getText()));
|
||||
case ERROR -> result.append(String.format("[ERROR] %s\n", message.getText()));
|
||||
case INFO -> result.append(String.format("[INFO] %s\n", message.getText()));
|
||||
default -> result.append(String.format("[ERROR] %s\n", "Unexpected message type: " + message.getType()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public enum MessageType {
|
||||
INFO, MESSAGE, ERROR;
|
||||
public void clear() {
|
||||
messages = new ArrayList<>();
|
||||
changed.set(!changed.get());
|
||||
}
|
||||
|
||||
public SimpleBooleanProperty getChangedProperty() { return changed; }
|
||||
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import javafx.scene.layout.Pane;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
public class ClientUI extends Application {
|
||||
private ClientMessageList clientMessageList = new ClientMessageList();
|
||||
|
||||
@Override
|
||||
public void start(Stage primaryStage) {
|
||||
@@ -17,6 +18,10 @@ public class ClientUI extends Application {
|
||||
try {
|
||||
FXMLLoader loader = new FXMLLoader(getClass().getResource("ChatWindow.fxml"));
|
||||
Pane rootPane = loader.load();
|
||||
|
||||
ChatWindowController chatWindowController = loader.getController();
|
||||
chatWindowController.setMessages(clientMessageList);
|
||||
|
||||
// fill in scene and stage setup
|
||||
Scene scene = new Scene(rootPane);
|
||||
//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;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import java.io.IOException;
|
||||
import java.net.SocketException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
|
||||
public class Server {
|
||||
@@ -62,23 +64,34 @@ public class Server {
|
||||
}
|
||||
|
||||
private void start() {
|
||||
ReentrantLock mutex = new ReentrantLock();
|
||||
Condition nameComplete = mutex.newCondition();
|
||||
System.out.println("Server started.");
|
||||
try {
|
||||
while (true) {
|
||||
NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection();
|
||||
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections);
|
||||
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections, mutex, nameComplete);
|
||||
new Thread(connectionHandler).start();
|
||||
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
|
||||
connectionHandler.getUserName(),
|
||||
connection.getRemoteHost(),
|
||||
connection.getRemotePort()
|
||||
));
|
||||
mutex.lock();
|
||||
try {
|
||||
nameComplete.await();
|
||||
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) {
|
||||
System.out.println("Server connection terminated");
|
||||
}
|
||||
catch (IOException e) {
|
||||
System.err.println("Communication error " + e);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
// close server
|
||||
System.out.println("Server Stopped.");
|
||||
|
||||
@@ -11,6 +11,8 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Scanner;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
|
||||
|
||||
@@ -30,6 +32,10 @@ public class ServerConnectionHandler implements Runnable{
|
||||
private static final String USER_NONE = "";
|
||||
private static final String USER_ALL = "*";
|
||||
|
||||
private ReentrantLock mutex;
|
||||
|
||||
private Condition nameComplete;
|
||||
|
||||
private String userName = "Anonymous-"+connectionId;
|
||||
private State state = NEW;
|
||||
|
||||
@@ -43,11 +49,13 @@ public class ServerConnectionHandler implements Runnable{
|
||||
}
|
||||
|
||||
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
||||
Map<String,ServerConnectionHandler> registry) {
|
||||
Map<String,ServerConnectionHandler> registry, ReentrantLock mutex, Condition nameComplete) {
|
||||
Objects.requireNonNull(connection, "Connection must not be null");
|
||||
Objects.requireNonNull(registry, "Registry must not be null");
|
||||
this.connection = connection;
|
||||
this.connectionRegistry = registry;
|
||||
this.mutex = mutex;
|
||||
this.nameComplete = nameComplete;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
@@ -55,28 +63,29 @@ public class ServerConnectionHandler implements Runnable{
|
||||
}
|
||||
|
||||
public void startReceiving() {
|
||||
System.out.println("Starting Connection Handler for " + userName);
|
||||
try {
|
||||
System.out.println("Start receiving data...");
|
||||
while (connection.isAvailable()) {
|
||||
String data = connection.receive();
|
||||
processData(data);
|
||||
System.out.println("Starting Connection Handler for new User");
|
||||
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("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);
|
||||
System.out.println("Stopping Connection Handler for " + userName);
|
||||
|
||||
}
|
||||
|
||||
public void stopReceiving() {
|
||||
@@ -124,7 +133,14 @@ public class ServerConnectionHandler implements Runnable{
|
||||
if (sender == null || sender.isBlank()) sender = this.userName;
|
||||
if (connectionRegistry.containsKey(sender))
|
||||
throw new ChatProtocolException("User name already taken: " + sender);
|
||||
this.userName = sender;
|
||||
mutex.lock();
|
||||
try {
|
||||
this.userName = sender;
|
||||
nameComplete.signal();
|
||||
}
|
||||
finally {
|
||||
mutex.unlock();
|
||||
}
|
||||
connectionRegistry.put(userName, this);
|
||||
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Registration successfull for " + userName);
|
||||
this.state = CONNECTED;
|
||||
@@ -149,6 +165,9 @@ public class ServerConnectionHandler implements Runnable{
|
||||
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, DATA_TYPE_ERROR, "Unknown User: " + reciever);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user