fixed issue #39

This commit is contained in:
Andrin Fassbind 2022-04-15 21:13:28 +02:00 committed by Leonardo Brandenberger
parent 5c0e55870d
commit add410250f
2 changed files with 12 additions and 38 deletions

View File

@ -94,32 +94,11 @@ public class Server {
NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection();
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections, mutex, nameComplete);
new Thread(connectionHandler).start();
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()));
}
}
finally {
mutex.unlock();
}
}
} catch(SocketException e) {
System.out.println("Server connection terminated");
}
catch (IOException e) {
} catch (IOException e) {
System.err.println("Communication error " + e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// close server
System.out.println("Server Stopped.");

View File

@ -194,28 +194,23 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
private void caseConnect(String sender) throws ChatProtocolException {
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
if (sender.isBlank()) sender = this.userName;
//if username not valid
if (connectionRegistry.containsKey(sender)) {
mutex.lock();
try {
state = ERROR;
nameComplete.signal();
}
finally {
mutex.unlock();
}
state = ERROR;
System.out.println(String.format("Connecting failed for new Client with IP:Port <%s:%d>.\nReason: Name already taken.",
getConnection().getRemoteHost(),
getConnection().getRemotePort()));
throw new ChatProtocolException("User name already taken: " + sender);
}
mutex.lock();
try {
this.userName = sender;
nameComplete.signal();
}
finally {
mutex.unlock();
}
//if username valid
this.userName = sender;
connectionRegistry.put(userName, this);
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
this.state = CONNECTED;
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
userName,
getConnection().getRemoteHost(),
getConnection().getRemotePort()));
}
/**