Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6fd5b569d | ||
|
|
b47d98b960 |
@@ -1,8 +1,7 @@
|
|||||||
package ch.zhaw.pm2.multichat.client;
|
package ch.zhaw.pm2.multichat.client;
|
||||||
|
|
||||||
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State;
|
import ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State;
|
||||||
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
import ch.zhaw.pm2.multichat.protocol.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.ChangeListener;
|
||||||
@@ -16,8 +15,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.protocol.ConnectionHandler.State.*;
|
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
||||||
|
|
||||||
public class ChatWindowController {
|
public class ChatWindowController {
|
||||||
private ClientConnectionHandler connectionHandler;
|
private ClientConnectionHandler connectionHandler;
|
||||||
@@ -48,7 +49,7 @@ public class ChatWindowController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void applicationClose() {
|
private void applicationClose() {
|
||||||
disconnect();
|
connectionHandler.setState(DISCONNECTED);
|
||||||
}
|
}
|
||||||
|
|
||||||
@FXML
|
@FXML
|
||||||
@@ -105,6 +106,7 @@ public class ChatWindowController {
|
|||||||
|
|
||||||
private void startConnectionHandler() throws IOException {
|
private void startConnectionHandler() throws IOException {
|
||||||
String userName = userNameField.getText();
|
String userName = userNameField.getText();
|
||||||
|
if(!userName.contains(" ")) {
|
||||||
String serverAddress = serverAddressField.getText();
|
String serverAddress = serverAddressField.getText();
|
||||||
int serverPort = Integer.parseInt(serverPortField.getText());
|
int serverPort = Integer.parseInt(serverPortField.getText());
|
||||||
connectionHandler = new ClientConnectionHandler(
|
connectionHandler = new ClientConnectionHandler(
|
||||||
@@ -117,6 +119,9 @@ public class ChatWindowController {
|
|||||||
|
|
||||||
// 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);
|
||||||
|
} else {
|
||||||
|
addError("It is not allowed to have spaces in username!");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void terminateConnectionHandler() {
|
private void terminateConnectionHandler() {
|
||||||
@@ -128,7 +133,7 @@ public class ChatWindowController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stateChanged(ConnectionHandler.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() {
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
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;
|
||||||
@@ -13,11 +12,23 @@ 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.*;
|
|
||||||
|
|
||||||
public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
|
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
||||||
|
|
||||||
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
|
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 SimpleStringProperty userName;
|
private SimpleStringProperty userName;
|
||||||
private SimpleObjectProperty<State> state;
|
private SimpleObjectProperty<State> state;
|
||||||
@@ -25,13 +36,17 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
private SimpleStringProperty serverAddress;
|
private SimpleStringProperty serverAddress;
|
||||||
private SimpleIntegerProperty serverPort;
|
private SimpleIntegerProperty serverPort;
|
||||||
|
|
||||||
|
enum State {
|
||||||
|
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
|
||||||
|
}
|
||||||
|
|
||||||
public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
||||||
String userName,
|
String userName,
|
||||||
ClientMessageList messages) {
|
ClientMessageList messages) {
|
||||||
super(connection);
|
this.connection = connection;
|
||||||
this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName);
|
this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName);
|
||||||
this.messages = messages;
|
this.messages = messages;
|
||||||
state = new SimpleObjectProperty<>(State.NEW);
|
state = new SimpleObjectProperty<>(NEW);
|
||||||
serverAddress = new SimpleStringProperty();
|
serverAddress = new SimpleStringProperty();
|
||||||
serverPort = new SimpleIntegerProperty();
|
serverPort = new SimpleIntegerProperty();
|
||||||
}
|
}
|
||||||
@@ -48,19 +63,18 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
|
|
||||||
public void setState (State newState) {
|
public void setState (State newState) {
|
||||||
state.set(newState);
|
state.set(newState);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void run () {
|
public void run () {
|
||||||
startReceiving();
|
startReceiving();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void startReceiving() {
|
public 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 (getConnection().isAvailable()) {
|
while (connection.isAvailable()) {
|
||||||
String data = getConnection().receive();
|
String data = connection.receive();
|
||||||
processData(data);
|
processData(data);
|
||||||
}
|
}
|
||||||
System.out.println("Stopped recieving data");
|
System.out.println("Stopped recieving data");
|
||||||
@@ -84,7 +98,7 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
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...");
|
||||||
getConnection().close();
|
connection.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());
|
||||||
@@ -119,13 +133,13 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
payload = scanner.nextLine();
|
payload = scanner.nextLine();
|
||||||
}
|
}
|
||||||
// dispatch operation based on type parameter
|
// dispatch operation based on type parameter
|
||||||
if (type.equals(getDataTypeConnect())) {
|
if (type.equals(DATA_TYPE_CONNECT)) {
|
||||||
System.err.println("Illegal connect request from server");
|
System.err.println("Illegal connect request from server");
|
||||||
} else if (type.equals(getDataTypeConfirm())) {
|
} else if (type.equals(DATA_TYPE_CONFIRM)) {
|
||||||
if (state.get() == CONFIRM_CONNECT) {
|
if (state.get() == CONFIRM_CONNECT) {
|
||||||
this.userName.set(reciever);
|
this.userName.set(reciever);
|
||||||
this.serverPort.set(getConnection().getRemotePort());
|
this.serverPort.set(connection.getRemotePort());
|
||||||
this.serverAddress.set(getConnection().getRemoteHost());
|
this.serverAddress.set(connection.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);
|
||||||
@@ -136,7 +150,7 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
} else {
|
} else {
|
||||||
System.err.println("Got unexpected confirm message: " + payload);
|
System.err.println("Got unexpected confirm message: " + payload);
|
||||||
}
|
}
|
||||||
} else if (type.equals(getDataTypeDisconnect())) {
|
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
|
||||||
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;
|
||||||
@@ -144,14 +158,14 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
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(getDataTypeMessage())) {
|
} else if (type.equals(DATA_TYPE_MESSAGE)) {
|
||||||
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(getDataTypeError())) {
|
} else if (type.equals(DATA_TYPE_ERROR)) {
|
||||||
messages.addMessage(new Message(Message.MessageType.ERROR,sender,reciever,payload));
|
messages.addMessage(new Message(Message.MessageType.ERROR,sender,reciever,payload));
|
||||||
System.out.println("ERROR: " + payload);
|
System.out.println("ERROR: " + payload);
|
||||||
} else {
|
} else {
|
||||||
@@ -159,12 +173,12 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
}
|
}
|
||||||
} 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.get(), getDataTypeError(), e.getMessage());
|
sendData(USER_NONE, userName.get(), DATA_TYPE_ERROR, e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendData(String sender, String receiver, String type, String payload) {
|
public void sendData(String sender, String receiver, String type, String payload) {
|
||||||
if (getConnection().isAvailable()) {
|
if (connection.isAvailable()) {
|
||||||
new StringBuilder();
|
new StringBuilder();
|
||||||
String data = new StringBuilder()
|
String data = new StringBuilder()
|
||||||
.append(sender+"\n")
|
.append(sender+"\n")
|
||||||
@@ -173,7 +187,7 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
.append(payload+"\n")
|
.append(payload+"\n")
|
||||||
.toString();
|
.toString();
|
||||||
try {
|
try {
|
||||||
getConnection().send(data);
|
connection.send(data);
|
||||||
} catch (SocketException e) {
|
} catch (SocketException e) {
|
||||||
System.err.println("Connection closed: " + e.getMessage());
|
System.err.println("Connection closed: " + e.getMessage());
|
||||||
} catch (EOFException e) {
|
} catch (EOFException e) {
|
||||||
@@ -186,13 +200,13 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
|
|
||||||
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, getDataTypeConnect(),null);
|
this.sendData(userName.get(), USER_NONE, DATA_TYPE_CONNECT,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, getDataTypeDisconnect(),null);
|
this.sendData(userName.get(), USER_NONE, DATA_TYPE_DISCONNECT,null);
|
||||||
this.setState(CONFIRM_DISCONNECT);
|
this.setState(CONFIRM_DISCONNECT);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,7 +221,7 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
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, getDataTypeMessage(),message);
|
this.sendData(userName.get(), receiver, DATA_TYPE_MESSAGE,message);
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
package ch.zhaw.pm2.multichat.protocol;
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ConnectionHandler(NetworkHandler.NetworkConnection<String> connection) {
|
|
||||||
this.connection = connection;
|
|
||||||
}
|
|
||||||
|
|
||||||
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() {
|
|
||||||
this.connection = connection;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,8 +6,6 @@ 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 {
|
||||||
@@ -64,34 +62,23 @@ 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, mutex, nameComplete);
|
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections);
|
||||||
new Thread(connectionHandler).start();
|
new Thread(connectionHandler).start();
|
||||||
mutex.lock();
|
|
||||||
try {
|
|
||||||
nameComplete.await();
|
|
||||||
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
|
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
|
||||||
connectionHandler.getUserName(),
|
connectionHandler.getUserName(),
|
||||||
connection.getRemoteHost(),
|
connection.getRemoteHost(),
|
||||||
connection.getRemotePort()
|
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,7 +1,6 @@
|
|||||||
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 ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||||
|
|
||||||
import java.io.EOFException;
|
import java.io.EOFException;
|
||||||
@@ -12,19 +11,24 @@ 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.*;
|
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
|
||||||
|
|
||||||
public class ServerConnectionHandler extends ConnectionHandler implements Runnable{
|
public class ServerConnectionHandler implements Runnable{
|
||||||
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
|
private 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;
|
||||||
|
|
||||||
private ReentrantLock mutex;
|
// Data types used for the Chat Protocol
|
||||||
|
private static final String DATA_TYPE_CONNECT = "CONNECT";
|
||||||
|
private static final String DATA_TYPE_CONFIRM = "CONFIRM";
|
||||||
|
private static final String DATA_TYPE_DISCONNECT = "DISCONNECT";
|
||||||
|
private static final String DATA_TYPE_MESSAGE = "MESSAGE";
|
||||||
|
private static final String DATA_TYPE_ERROR = "ERROR";
|
||||||
|
|
||||||
private Condition nameComplete;
|
private static final String USER_NONE = "";
|
||||||
|
private static final String USER_ALL = "*";
|
||||||
|
|
||||||
private String userName = "Anonymous-"+connectionId;
|
private String userName = "Anonymous-"+connectionId;
|
||||||
private State state = NEW;
|
private State state = NEW;
|
||||||
@@ -39,25 +43,23 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
||||||
Map<String,ServerConnectionHandler> registry, ReentrantLock mutex, Condition nameComplete) {
|
Map<String,ServerConnectionHandler> registry) {
|
||||||
super(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;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void startReceiving() {
|
public 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 (getConnection().isAvailable()) {
|
while (connection.isAvailable()) {
|
||||||
String data = getConnection().receive();
|
String data = connection.receive();
|
||||||
processData(data);
|
processData(data);
|
||||||
}
|
}
|
||||||
System.out.println("Stopped recieving data");
|
System.out.println("Stopped recieving data");
|
||||||
@@ -69,20 +71,19 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
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());
|
||||||
}
|
}
|
||||||
System.out.println("Stopping Connection Handler for " + userName);
|
System.out.println("Stopping Connection Handler for " + userName);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void stopReceiving() {
|
public 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...");
|
||||||
getConnection().close();
|
connection.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);
|
||||||
@@ -118,34 +119,27 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
}
|
}
|
||||||
|
|
||||||
// dispatch operation based on type parameter
|
// dispatch operation based on type parameter
|
||||||
if (type.equals(getDataTypeConnect())) {
|
if (type.equals(DATA_TYPE_CONNECT)) {
|
||||||
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 == null || sender.isBlank()) sender = this.userName;
|
||||||
if (connectionRegistry.containsKey(sender))
|
if (connectionRegistry.containsKey(sender))
|
||||||
throw new ChatProtocolException("User name already taken: " + sender);
|
throw new ChatProtocolException("User name already taken: " + sender);
|
||||||
mutex.lock();
|
|
||||||
try {
|
|
||||||
this.userName = sender;
|
this.userName = sender;
|
||||||
nameComplete.signal();
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
mutex.unlock();
|
|
||||||
}
|
|
||||||
connectionRegistry.put(userName, this);
|
connectionRegistry.put(userName, this);
|
||||||
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
|
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Registration successfull for " + userName);
|
||||||
this.state = CONNECTED;
|
this.state = CONNECTED;
|
||||||
} else if (type.equals(getDataTypeConfirm())) {
|
} 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(getDataTypeDisconnect())) {
|
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
|
||||||
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, getDataTypeConfirm(), "Confirm disconnect of " + userName);
|
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Confirm disconnect of " + userName);
|
||||||
this.state = DISCONNECTED;
|
this.state = DISCONNECTED;
|
||||||
this.stopReceiving();
|
this.stopReceiving();
|
||||||
} else if (type.equals(getDataTypeMessage())) {
|
} else if (type.equals(DATA_TYPE_MESSAGE)) {
|
||||||
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()) {
|
||||||
@@ -159,10 +153,10 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
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, getDataTypeError(), "Unknown User: " + reciever);
|
this.sendData(USER_NONE, userName, DATA_TYPE_ERROR, "Unknown User: " + reciever);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (type.equals(getDataTypeError())) {
|
} 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);
|
||||||
@@ -170,12 +164,12 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
}
|
}
|
||||||
} 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, getDataTypeError(), e.getMessage());
|
sendData(USER_NONE, userName, DATA_TYPE_ERROR, e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendData(String sender, String receiver, String type, String payload) {
|
public void sendData(String sender, String receiver, String type, String payload) {
|
||||||
if (getConnection().isAvailable()) {
|
if (connection.isAvailable()) {
|
||||||
new StringBuilder();
|
new StringBuilder();
|
||||||
String data = new StringBuilder()
|
String data = new StringBuilder()
|
||||||
.append(sender+"\n")
|
.append(sender+"\n")
|
||||||
@@ -184,7 +178,7 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
.append(payload+"\n")
|
.append(payload+"\n")
|
||||||
.toString();
|
.toString();
|
||||||
try {
|
try {
|
||||||
getConnection().send(data);
|
connection.send(data);
|
||||||
} catch (SocketException e) {
|
} catch (SocketException e) {
|
||||||
System.out.println("Connection closed: " + e.getMessage());
|
System.out.println("Connection closed: " + e.getMessage());
|
||||||
} catch (EOFException e) {
|
} catch (EOFException e) {
|
||||||
|
|||||||
Reference in New Issue
Block a user