Посмотрел в обсуждении и в аналогичных вопросах по этой задаче, но ответа не нашел или не понял. Почему не проходит последний пункт? Метод вернёт имя клиента только в случае успешного соединения, null возвращать не должен.
package com.javarush.task.task30.task3008;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Server {
private static Map<String, Connection> connectionMap = new ConcurrentHashMap<>();
public static void main(String[] args) {
int serverPort = ConsoleHelper.readInt();
try (ServerSocket serverSocket = new ServerSocket(serverPort)) {
ConsoleHelper.writeMessage("Сервер начал работу");
while (true) {
new Handler(serverSocket.accept()).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sendBroadcastMessage(Message message) {
for (Map.Entry<String, Connection> pair : connectionMap.entrySet()) {
try {
pair.getValue().send(message);
} catch (IOException e) {
ConsoleHelper.writeMessage("Сообщение не отправлено");
}
}
}
private static class Handler extends Thread {
private Socket socket;
public Handler(Socket socket) {
this.socket = socket;
}
private String serverHandshake(Connection connection) throws IOException, ClassNotFoundException {
String clientName = null;
connection.send(new Message(MessageType.NAME_REQUEST, "Введите имя пользователя"));
Message receive = connection.receive();
if (receive.getType() != MessageType.USER_NAME) {
serverHandshake(connection);
} else {
// тут решил перестраховаться
if (receive.getData().isEmpty() || receive.getData() == null || receive.getData().equals("")){
ConsoleHelper.writeMessage("Введите имя");
serverHandshake(connection);
} else if (connectionMap.containsKey(receive.getData())) {
ConsoleHelper.writeMessage("Имя уже занято");
serverHandshake(connection);
} else {
clientName = receive.getData();
connectionMap.put(clientName, connection);
connection.send(new Message(MessageType.NAME_ACCEPTED, "Имя принято"));
}
}
return clientName;
}
}
}