Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a534b2465 | ||
|
|
37045ade15 | ||
|
|
a75d3466ef | ||
|
|
97b6fff82e | ||
|
|
2a8b701f48 | ||
|
|
86aa801b34 | ||
|
|
2277fee73a | ||
|
|
d8dbd93c15 | ||
|
|
6e8e560d73 | ||
|
|
615b3844e3 | ||
|
|
4a998b0f61 | ||
|
|
b6fd5b569d | ||
|
|
b47d98b960 |
@@ -47,6 +47,10 @@ public class ChatWindowController {
|
|||||||
messageListener();
|
messageListener();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setConnectionHandler(ClientConnectionHandler connectionHandler){
|
||||||
|
this.connectionHandler = connectionHandler;
|
||||||
|
}
|
||||||
|
|
||||||
private void applicationClose() {
|
private void applicationClose() {
|
||||||
disconnect();
|
disconnect();
|
||||||
}
|
}
|
||||||
@@ -105,11 +109,10 @@ 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.initialize(serverAddress, serverPort, userName);
|
||||||
NetworkHandler.openConnection(serverAddress, serverPort), userName,
|
|
||||||
messages);
|
|
||||||
new Thread(connectionHandler).start();
|
new Thread(connectionHandler).start();
|
||||||
|
|
||||||
//register Listener
|
//register Listener
|
||||||
@@ -117,18 +120,12 @@ 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() {
|
|
||||||
// unregister window close handler
|
|
||||||
rootPane.getScene().getWindow().removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
|
|
||||||
if (connectionHandler != null) {
|
|
||||||
connectionHandler.stopReceiving();
|
|
||||||
connectionHandler = null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
@@ -136,8 +133,8 @@ public class ChatWindowController {
|
|||||||
connectButton.setText((newState == CONNECTED || newState == CONFIRM_DISCONNECT) ? "Disconnect" : "Connect");
|
connectButton.setText((newState == CONNECTED || newState == CONFIRM_DISCONNECT) ? "Disconnect" : "Connect");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (newState == DISCONNECTED) {
|
if(newState == DISCONNECTED){
|
||||||
terminateConnectionHandler();
|
connectionHandler.stopReceiving();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
|
|||||||
|
|
||||||
public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
|
public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
|
||||||
|
|
||||||
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
|
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\S*))?\\s*(.*)$" );
|
||||||
|
|
||||||
private SimpleStringProperty userName;
|
private SimpleStringProperty userName;
|
||||||
private SimpleObjectProperty<State> state;
|
private SimpleObjectProperty<State> state;
|
||||||
@@ -25,15 +25,21 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
private SimpleStringProperty serverAddress;
|
private SimpleStringProperty serverAddress;
|
||||||
private SimpleIntegerProperty serverPort;
|
private SimpleIntegerProperty serverPort;
|
||||||
|
|
||||||
public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
public ClientConnectionHandler(ClientMessageList messages) {
|
||||||
String userName,
|
super();
|
||||||
ClientMessageList messages) {
|
|
||||||
super(connection);
|
|
||||||
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<>(State.NEW);
|
||||||
serverAddress = new SimpleStringProperty();
|
serverAddress = new SimpleStringProperty(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
|
||||||
serverPort = new SimpleIntegerProperty();
|
serverPort = new SimpleIntegerProperty(NetworkHandler.DEFAULT_PORT);
|
||||||
|
this.userName = new SimpleStringProperty(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
public SimpleStringProperty getServerAddressProperty() { return serverAddress; }
|
public SimpleStringProperty getServerAddressProperty() { return serverAddress; }
|
||||||
@@ -48,7 +54,6 @@ 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 () {
|
||||||
@@ -94,34 +99,34 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
|
|
||||||
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(getDataTypeConnect())) {
|
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(getDataTypeConfirm())) {
|
} 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(getConnection().getRemotePort());
|
this.serverPort.set(getConnection().getRemotePort());
|
||||||
@@ -136,7 +141,9 @@ 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())) {
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
@@ -144,44 +151,20 @@ 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())) {
|
}
|
||||||
|
|
||||||
|
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(getDataTypeError())) {
|
|
||||||
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(), getDataTypeError(), e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendData(String sender, String receiver, String type, String payload) {
|
private void caseError(String sender, String reciever, String payload) {
|
||||||
if (getConnection().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 {
|
|
||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void connect() throws ChatProtocolException {
|
public void connect() throws ChatProtocolException {
|
||||||
@@ -213,5 +196,4 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
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);
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
package ch.zhaw.pm2.multichat.protocol;
|
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 {
|
public abstract class ConnectionHandler {
|
||||||
private NetworkHandler.NetworkConnection<String> connection;
|
private NetworkHandler.NetworkConnection<String> connection;
|
||||||
|
|
||||||
@@ -14,11 +19,7 @@ public abstract class ConnectionHandler {
|
|||||||
public static final String USER_ALL = "*";
|
public static final String USER_ALL = "*";
|
||||||
|
|
||||||
public enum State {
|
public enum State {
|
||||||
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
|
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED, ERROR;
|
||||||
}
|
|
||||||
|
|
||||||
public ConnectionHandler(NetworkHandler.NetworkConnection<String> connection) {
|
|
||||||
this.connection = connection;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getDataTypeConnect() {
|
public static String getDataTypeConnect() {
|
||||||
@@ -45,7 +46,50 @@ public abstract class ConnectionHandler {
|
|||||||
return connection;
|
return connection;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void setConnection() {
|
protected void setConnection(NetworkHandler.NetworkConnection<String> connection) {
|
||||||
this.connection = 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;
|
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;
|
||||||
@@ -75,11 +76,17 @@ public class Server {
|
|||||||
mutex.lock();
|
mutex.lock();
|
||||||
try {
|
try {
|
||||||
nameComplete.await();
|
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>",
|
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 {
|
finally {
|
||||||
mutex.unlock();
|
mutex.unlock();
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ 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.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;
|
||||||
@@ -15,7 +15,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||||||
import java.util.concurrent.locks.Condition;
|
import java.util.concurrent.locks.Condition;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
|
|
||||||
|
|
||||||
public class ServerConnectionHandler extends ConnectionHandler implements Runnable{
|
public class ServerConnectionHandler extends ConnectionHandler implements Runnable{
|
||||||
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
|
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
|
||||||
@@ -34,13 +34,10 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
startReceiving();
|
startReceiving();
|
||||||
}
|
}
|
||||||
|
|
||||||
enum State {
|
|
||||||
NEW, CONNECTED, DISCONNECTED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
|
||||||
Map<String,ServerConnectionHandler> registry, ReentrantLock mutex, Condition nameComplete) {
|
Map<String,ServerConnectionHandler> registry, ReentrantLock mutex, Condition nameComplete) {
|
||||||
super(connection);
|
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.connectionRegistry = registry;
|
this.connectionRegistry = registry;
|
||||||
@@ -52,11 +49,15 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
return this.userName;
|
return this.userName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public State getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
private void startReceiving() {
|
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 (getConnection().isAvailable()) {
|
while (getConnection().isAvailable() && !(state == ERROR)) {
|
||||||
String data = getConnection().receive();
|
String data = getConnection().receive();
|
||||||
processData(data);
|
processData(data);
|
||||||
}
|
}
|
||||||
@@ -74,7 +75,11 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
} 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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,47 +90,58 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
getConnection().close();
|
getConnection().close();
|
||||||
System.out.println("Stopped receiving data.");
|
System.out.println("Stopped receiving data.");
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("Failed to close connection." + e);
|
System.err.println("Failed to close connection." + e.getMessage());
|
||||||
}
|
}
|
||||||
System.out.println("Closed Connection Handler for " + userName);
|
System.out.println("Closed Connection Handler for " + userName);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void processData(String data) {
|
private void processData(String data) {
|
||||||
try {
|
try {
|
||||||
// parse data content
|
|
||||||
Scanner scanner = new Scanner(data);
|
Scanner scanner = new Scanner(data);
|
||||||
String sender = null;
|
StringBuilder sender = new StringBuilder();
|
||||||
String reciever = null;
|
StringBuilder reciever = new StringBuilder();
|
||||||
String type = null;
|
StringBuilder type = new StringBuilder();
|
||||||
String payload = null;
|
StringBuilder payload = new StringBuilder();
|
||||||
if (scanner.hasNextLine()) {
|
super.processData(scanner,sender,reciever,type,payload);
|
||||||
sender = scanner.nextLine();
|
|
||||||
} else {
|
|
||||||
throw new ChatProtocolException("No Sender found");
|
|
||||||
}
|
|
||||||
if (scanner.hasNextLine()) {
|
|
||||||
reciever = scanner.nextLine();
|
|
||||||
} else {
|
|
||||||
throw new ChatProtocolException("No Reciever found");
|
|
||||||
}
|
|
||||||
if (scanner.hasNextLine()) {
|
|
||||||
type = scanner.nextLine();
|
|
||||||
} else {
|
|
||||||
throw new ChatProtocolException("No Type found");
|
|
||||||
}
|
|
||||||
if (scanner.hasNextLine()) {
|
|
||||||
payload = scanner.nextLine();
|
|
||||||
}
|
|
||||||
|
|
||||||
// dispatch operation based on type parameter
|
// dispatch operation based on type parameter
|
||||||
if (type.equals(getDataTypeConnect())) {
|
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 (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 (connectionRegistry.containsKey(sender)) {
|
||||||
throw new ChatProtocolException("User name already taken: " + sender);
|
|
||||||
mutex.lock();
|
mutex.lock();
|
||||||
try {
|
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();
|
nameComplete.signal();
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
@@ -134,9 +150,9 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
connectionRegistry.put(userName, this);
|
connectionRegistry.put(userName, this);
|
||||||
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
|
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
|
||||||
this.state = CONNECTED;
|
this.state = CONNECTED;
|
||||||
} else if (type.equals(getDataTypeConfirm())) {
|
}
|
||||||
System.out.println("Not expecting to receive a CONFIRM request from client");
|
|
||||||
} else if (type.equals(getDataTypeDisconnect())) {
|
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) {
|
||||||
@@ -145,7 +161,9 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
sendData(USER_NONE, userName, getDataTypeConfirm(), "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(getDataTypeMessage())) {
|
}
|
||||||
|
|
||||||
|
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()) {
|
||||||
@@ -162,36 +180,5 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
|
|||||||
this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + reciever);
|
this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + reciever);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (type.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 sendData(String sender, String receiver, String type, String payload) {
|
|
||||||
if (getConnection().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.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