Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a534b2465 | ||
|
|
37045ade15 | ||
|
|
a75d3466ef | ||
|
|
97b6fff82e | ||
|
|
2a8b701f48 | ||
|
|
86aa801b34 | ||
|
|
2277fee73a | ||
|
|
d8dbd93c15 | ||
|
|
6e8e560d73 | ||
|
|
5a26c6b127 | ||
|
|
615b3844e3 | ||
|
|
5e6e9d5817 | ||
|
|
4a998b0f61 | ||
|
|
af46e499ff | ||
|
|
b6fd5b569d | ||
|
|
b47d98b960 |
@@ -1,7 +1,8 @@
|
||||
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.ConnectionHandler;
|
||||
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||
import javafx.application.Platform;
|
||||
import javafx.beans.value.ChangeListener;
|
||||
@@ -15,10 +16,8 @@ import javafx.scene.layout.Pane;
|
||||
import javafx.stage.WindowEvent;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
|
||||
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
|
||||
|
||||
public class ChatWindowController {
|
||||
private ClientConnectionHandler connectionHandler;
|
||||
@@ -48,6 +47,10 @@ public class ChatWindowController {
|
||||
messageListener();
|
||||
}
|
||||
|
||||
public void setConnectionHandler(ClientConnectionHandler connectionHandler){
|
||||
this.connectionHandler = connectionHandler;
|
||||
}
|
||||
|
||||
private void applicationClose() {
|
||||
disconnect();
|
||||
}
|
||||
@@ -106,11 +109,10 @@ public class ChatWindowController {
|
||||
|
||||
private void startConnectionHandler() throws IOException {
|
||||
String userName = userNameField.getText();
|
||||
if(!userName.contains(" ")) {
|
||||
String serverAddress = serverAddressField.getText();
|
||||
int serverPort = Integer.parseInt(serverPortField.getText());
|
||||
connectionHandler = new ClientConnectionHandler(
|
||||
NetworkHandler.openConnection(serverAddress, serverPort), userName,
|
||||
messages);
|
||||
connectionHandler.initialize(serverAddress, serverPort, userName);
|
||||
new Thread(connectionHandler).start();
|
||||
|
||||
//register Listener
|
||||
@@ -118,14 +120,8 @@ public class ChatWindowController {
|
||||
|
||||
// register window close handler
|
||||
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
||||
}
|
||||
|
||||
private void terminateConnectionHandler() {
|
||||
// unregister window close handler
|
||||
rootPane.getScene().getWindow().removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
||||
if (connectionHandler != null) {
|
||||
connectionHandler.stopReceiving();
|
||||
connectionHandler = null;
|
||||
} else {
|
||||
addError("It is not allowed to have spaces in username!");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +134,7 @@ public class ChatWindowController {
|
||||
}
|
||||
});
|
||||
if(newState == DISCONNECTED){
|
||||
terminateConnectionHandler();
|
||||
connectionHandler.stopReceiving();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package ch.zhaw.pm2.multichat.client;
|
||||
|
||||
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
||||
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
|
||||
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||
import javafx.beans.property.SimpleIntegerProperty;
|
||||
import javafx.beans.property.SimpleObjectProperty;
|
||||
@@ -12,23 +13,11 @@ import java.net.SocketException;
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
|
||||
|
||||
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( "^(?:@(\\w*))?\\s*(.*)$" );
|
||||
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\S*))?\\s*(.*)$" );
|
||||
|
||||
private SimpleStringProperty userName;
|
||||
private SimpleObjectProperty<State> state;
|
||||
@@ -36,19 +25,21 @@ public class ClientConnectionHandler implements Runnable {
|
||||
private SimpleStringProperty serverAddress;
|
||||
private SimpleIntegerProperty serverPort;
|
||||
|
||||
enum State {
|
||||
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
|
||||
public ClientConnectionHandler(ClientMessageList messages) {
|
||||
super();
|
||||
this.messages = messages;
|
||||
state = new SimpleObjectProperty<>(State.NEW);
|
||||
serverAddress = new SimpleStringProperty(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
|
||||
serverPort = new SimpleIntegerProperty(NetworkHandler.DEFAULT_PORT);
|
||||
this.userName = new SimpleStringProperty(null);
|
||||
}
|
||||
|
||||
public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
||||
String userName,
|
||||
ClientMessageList messages) {
|
||||
this.connection = connection;
|
||||
public void initialize(String serverAddress, int serverPort, String userName) throws IOException {
|
||||
state.set(NEW);
|
||||
this.serverAddress.set(serverAddress);
|
||||
this.serverPort.set(serverPort);
|
||||
setConnection(NetworkHandler.openConnection(serverAddress, serverPort));
|
||||
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 SimpleStringProperty getServerAddressProperty() { return serverAddress; }
|
||||
@@ -63,19 +54,18 @@ public class ClientConnectionHandler implements Runnable {
|
||||
|
||||
public void setState (State newState) {
|
||||
state.set(newState);
|
||||
|
||||
}
|
||||
|
||||
public void run () {
|
||||
startReceiving();
|
||||
}
|
||||
|
||||
public void startReceiving() {
|
||||
private void startReceiving() {
|
||||
System.out.println("Starting Connection Handler");
|
||||
try {
|
||||
System.out.println("Start receiving data...");
|
||||
while (connection.isAvailable()) {
|
||||
String data = connection.receive();
|
||||
while (getConnection().isAvailable()) {
|
||||
String data = getConnection().receive();
|
||||
processData(data);
|
||||
}
|
||||
System.out.println("Stopped recieving data");
|
||||
@@ -99,7 +89,7 @@ public class ClientConnectionHandler implements Runnable {
|
||||
System.out.println("Closing Connection Handler to Server");
|
||||
try {
|
||||
System.out.println("Stop receiving data...");
|
||||
connection.close();
|
||||
getConnection().close();
|
||||
System.out.println("Stopped receiving data.");
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to close connection." + e.getMessage());
|
||||
@@ -109,38 +99,38 @@ public class ClientConnectionHandler implements Runnable {
|
||||
|
||||
private void processData(String data) {
|
||||
try {
|
||||
// parse data content
|
||||
Scanner scanner = new Scanner(data);
|
||||
String sender = null;
|
||||
String reciever = null;
|
||||
String type = null;
|
||||
String payload = null;
|
||||
if (scanner.hasNextLine()) {
|
||||
sender = scanner.nextLine();
|
||||
} else {
|
||||
throw new ChatProtocolException("No Sender found");
|
||||
}
|
||||
if (scanner.hasNextLine()) {
|
||||
reciever = scanner.nextLine();
|
||||
} else {
|
||||
throw new ChatProtocolException("No Reciever found");
|
||||
}
|
||||
if (scanner.hasNextLine()) {
|
||||
type = scanner.nextLine();
|
||||
} else {
|
||||
throw new ChatProtocolException("No Type found");
|
||||
}
|
||||
if (scanner.hasNextLine()) {
|
||||
payload = scanner.nextLine();
|
||||
}
|
||||
StringBuilder sender = new StringBuilder();
|
||||
StringBuilder reciever = new StringBuilder();
|
||||
StringBuilder type = new StringBuilder();
|
||||
StringBuilder payload = new StringBuilder();
|
||||
super.processData(scanner,sender,reciever,type,payload);
|
||||
|
||||
// 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");
|
||||
} 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) {
|
||||
this.userName.set(reciever);
|
||||
this.serverPort.set(connection.getRemotePort());
|
||||
this.serverAddress.set(connection.getRemoteHost());
|
||||
this.serverPort.set(getConnection().getRemotePort());
|
||||
this.serverAddress.set(getConnection().getRemoteHost());
|
||||
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
|
||||
System.out.println("CONFIRM: " + payload);
|
||||
this.setState(CONNECTED);
|
||||
@@ -151,7 +141,9 @@ public class ClientConnectionHandler implements Runnable {
|
||||
} else {
|
||||
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) {
|
||||
System.out.println("DISCONNECT: Already in disconnected: " + payload);
|
||||
return;
|
||||
@@ -159,55 +151,31 @@ public class ClientConnectionHandler implements Runnable {
|
||||
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)) {
|
||||
}
|
||||
|
||||
private void caseMessage(String sender, String reciever, String payload) {
|
||||
if (state.get() != CONNECTED) {
|
||||
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
|
||||
return;
|
||||
}
|
||||
messages.addMessage(new Message(Message.MessageType.MESSAGE,sender,reciever,payload));
|
||||
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
|
||||
} 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) {
|
||||
if (connection.isAvailable()) {
|
||||
new StringBuilder();
|
||||
String data = new StringBuilder()
|
||||
.append(sender+"\n")
|
||||
.append(receiver+"\n")
|
||||
.append(type+"\n")
|
||||
.append(payload+"\n")
|
||||
.toString();
|
||||
try {
|
||||
connection.send(data);
|
||||
} catch (SocketException e) {
|
||||
System.err.println("Connection closed: " + e.getMessage());
|
||||
} catch (EOFException e) {
|
||||
System.out.println("Connection terminated by remote");
|
||||
} catch(IOException e) {
|
||||
System.err.println("Communication error: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
private void caseError(String sender, String reciever, String payload) {
|
||||
messages.addMessage(new Message(Message.MessageType.ERROR,sender,reciever,payload));
|
||||
System.out.println("ERROR: " + payload);
|
||||
}
|
||||
|
||||
public void connect() throws ChatProtocolException {
|
||||
if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
|
||||
this.sendData(userName.get(), USER_NONE, DATA_TYPE_CONNECT,null);
|
||||
this.sendData(userName.get(), USER_NONE, getDataTypeConnect(),null);
|
||||
this.setState(CONFIRM_CONNECT);
|
||||
}
|
||||
|
||||
public void disconnect() throws ChatProtocolException {
|
||||
if (state.get() != NEW && state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + state);
|
||||
this.sendData(userName.get(), USER_NONE, DATA_TYPE_DISCONNECT,null);
|
||||
this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(),null);
|
||||
this.setState(CONFIRM_DISCONNECT);
|
||||
}
|
||||
|
||||
@@ -222,11 +190,10 @@ public class ClientConnectionHandler implements Runnable {
|
||||
return false;
|
||||
}
|
||||
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;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import javafx.stage.Stage;
|
||||
|
||||
public class ClientUI extends Application {
|
||||
private ClientMessageList clientMessageList = new ClientMessageList();
|
||||
private ClientConnectionHandler connectionHandler = new ClientConnectionHandler(clientMessageList);
|
||||
|
||||
@Override
|
||||
public void start(Stage primaryStage) {
|
||||
@@ -21,6 +22,7 @@ public class ClientUI extends Application {
|
||||
|
||||
ChatWindowController chatWindowController = loader.getController();
|
||||
chatWindowController.setMessages(clientMessageList);
|
||||
chatWindowController.setConnectionHandler(connectionHandler);
|
||||
|
||||
// fill in scene and stage setup
|
||||
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,5 +1,6 @@
|
||||
package ch.zhaw.pm2.multichat.server;
|
||||
|
||||
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
|
||||
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -75,11 +76,17 @@ public class Server {
|
||||
mutex.lock();
|
||||
try {
|
||||
nameComplete.await();
|
||||
if(connectionHandler.getState() == ConnectionHandler.State.ERROR) {
|
||||
System.out.println(String.format("Connecting failed for new Client with IP:Port <%s:%d>.\nReason: Name already taken.",
|
||||
connection.getRemoteHost(),
|
||||
connection.getRemotePort()));
|
||||
}
|
||||
else {
|
||||
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
|
||||
connectionHandler.getUserName(),
|
||||
connection.getRemoteHost(),
|
||||
connection.getRemotePort()
|
||||
));
|
||||
connection.getRemotePort()));
|
||||
}
|
||||
}
|
||||
finally {
|
||||
mutex.unlock();
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
package ch.zhaw.pm2.multichat.server;
|
||||
|
||||
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
|
||||
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
|
||||
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
|
||||
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
|
||||
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.net.SocketException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Scanner;
|
||||
@@ -14,24 +15,13 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
|
||||
|
||||
public class ServerConnectionHandler implements Runnable{
|
||||
|
||||
public class ServerConnectionHandler extends ConnectionHandler implements Runnable{
|
||||
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
|
||||
private final int connectionId = connectionCounter.incrementAndGet();
|
||||
private final NetworkHandler.NetworkConnection<String> connection;
|
||||
private final Map<String,ServerConnectionHandler> connectionRegistry;
|
||||
|
||||
// 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 static final String USER_NONE = "";
|
||||
private static final String USER_ALL = "*";
|
||||
|
||||
private ReentrantLock mutex;
|
||||
|
||||
private Condition nameComplete;
|
||||
@@ -44,15 +34,12 @@ public class ServerConnectionHandler implements Runnable{
|
||||
startReceiving();
|
||||
}
|
||||
|
||||
enum State {
|
||||
NEW, CONNECTED, DISCONNECTED;
|
||||
}
|
||||
|
||||
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
||||
Map<String,ServerConnectionHandler> registry, ReentrantLock mutex, Condition nameComplete) {
|
||||
super();
|
||||
setConnection(connection);
|
||||
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;
|
||||
@@ -62,12 +49,16 @@ public class ServerConnectionHandler implements Runnable{
|
||||
return this.userName;
|
||||
}
|
||||
|
||||
public void startReceiving() {
|
||||
public State getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
private void startReceiving() {
|
||||
System.out.println("Starting Connection Handler for new User");
|
||||
try {
|
||||
System.out.println("Start receiving data...");
|
||||
while (connection.isAvailable()) {
|
||||
String data = connection.receive();
|
||||
while (getConnection().isAvailable() && !(state == ERROR)) {
|
||||
String data = getConnection().receive();
|
||||
processData(data);
|
||||
}
|
||||
System.out.println("Stopped recieving data");
|
||||
@@ -84,78 +75,95 @@ public class ServerConnectionHandler implements Runnable{
|
||||
} catch (ClassNotFoundException e) {
|
||||
System.err.println("Received object of unknown type: " + e.getMessage());
|
||||
}
|
||||
if (state == ERROR) {
|
||||
System.out.println("Stopping Connection Handler for Rejected Client");
|
||||
} else {
|
||||
System.out.println("Stopping Connection Handler for " + userName);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void stopReceiving() {
|
||||
private void stopReceiving() {
|
||||
System.out.println("Closing Connection Handler for " + userName);
|
||||
try {
|
||||
System.out.println("Stop receiving data...");
|
||||
connection.close();
|
||||
getConnection().close();
|
||||
System.out.println("Stopped receiving data.");
|
||||
} 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);
|
||||
}
|
||||
|
||||
private void processData(String data) {
|
||||
try {
|
||||
// parse data content
|
||||
Scanner scanner = new Scanner(data);
|
||||
String sender = null;
|
||||
String reciever = null;
|
||||
String type = null;
|
||||
String payload = null;
|
||||
if (scanner.hasNextLine()) {
|
||||
sender = scanner.nextLine();
|
||||
} else {
|
||||
throw new ChatProtocolException("No Sender found");
|
||||
}
|
||||
if (scanner.hasNextLine()) {
|
||||
reciever = scanner.nextLine();
|
||||
} else {
|
||||
throw new ChatProtocolException("No Reciever found");
|
||||
}
|
||||
if (scanner.hasNextLine()) {
|
||||
type = scanner.nextLine();
|
||||
} else {
|
||||
throw new ChatProtocolException("No Type found");
|
||||
}
|
||||
if (scanner.hasNextLine()) {
|
||||
payload = scanner.nextLine();
|
||||
}
|
||||
StringBuilder sender = new StringBuilder();
|
||||
StringBuilder reciever = new StringBuilder();
|
||||
StringBuilder type = new StringBuilder();
|
||||
StringBuilder payload = new StringBuilder();
|
||||
super.processData(scanner,sender,reciever,type,payload);
|
||||
|
||||
// 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());
|
||||
}
|
||||
}
|
||||
|
||||
private void caseConnect(String sender) throws ChatProtocolException {
|
||||
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
|
||||
if (sender == null || sender.isBlank()) sender = this.userName;
|
||||
if (connectionRegistry.containsKey(sender))
|
||||
throw new ChatProtocolException("User name already taken: " + sender);
|
||||
if (sender.isBlank()) sender = this.userName;
|
||||
if (connectionRegistry.containsKey(sender)) {
|
||||
mutex.lock();
|
||||
try {
|
||||
this.userName = sender;
|
||||
state = ERROR;
|
||||
nameComplete.signal();
|
||||
}
|
||||
finally {
|
||||
mutex.unlock();
|
||||
}
|
||||
throw new ChatProtocolException("User name already taken: " + sender);
|
||||
}
|
||||
mutex.lock();
|
||||
try {
|
||||
this.userName = sender.toString();
|
||||
nameComplete.signal();
|
||||
}
|
||||
finally {
|
||||
mutex.unlock();
|
||||
}
|
||||
connectionRegistry.put(userName, this);
|
||||
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Registration successfull for " + userName);
|
||||
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
|
||||
this.state = CONNECTED;
|
||||
} else if (type.equals(DATA_TYPE_CONFIRM)) {
|
||||
System.out.println("Not expecting to receive a CONFIRM request from client");
|
||||
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
|
||||
}
|
||||
|
||||
private void caseDisconnect() throws ChatProtocolException {
|
||||
if (state == DISCONNECTED)
|
||||
throw new ChatProtocolException("Illegal state for disconnect request: " + state);
|
||||
if (state == CONNECTED) {
|
||||
connectionRegistry.remove(this.userName);
|
||||
}
|
||||
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Confirm disconnect of " + userName);
|
||||
sendData(USER_NONE, userName, getDataTypeConfirm(), "Confirm disconnect of " + userName);
|
||||
this.state = DISCONNECTED;
|
||||
this.stopReceiving();
|
||||
} else if (type.equals(DATA_TYPE_MESSAGE)) {
|
||||
}
|
||||
|
||||
private void caseMessage(String sender, String reciever, String type, String payload) throws ChatProtocolException{
|
||||
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state);
|
||||
if (USER_ALL.equals(reciever)) {
|
||||
for (ServerConnectionHandler handler : connectionRegistry.values()) {
|
||||
@@ -169,38 +177,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.
|
||||
}
|
||||
} else {
|
||||
this.sendData(USER_NONE, userName, DATA_TYPE_ERROR, "Unknown User: " + reciever);
|
||||
}
|
||||
}
|
||||
} else if (type.equals(DATA_TYPE_ERROR)) {
|
||||
System.err.println("Received error from client (" + sender + "): " + payload);
|
||||
} else {
|
||||
System.err.println("Unknown data type received: " + type);
|
||||
|
||||
}
|
||||
} catch(ChatProtocolException e) {
|
||||
System.out.println("Error while processing data" + e.getMessage());
|
||||
sendData(USER_NONE, userName, 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());
|
||||
this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + reciever);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user