How else do I call the notify method on the client object
package com.codegym.task.task30.task3008;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Server {
private static Map<String, Connection>connectionMap;
static{
connectionMap=new ConcurrentHashMap<>();
}
public static void main(String[] args){
ConsoleHelper.writeMessage("Input server port: ");
try (ServerSocket serverSocket = new ServerSocket(ConsoleHelper.readInt())){
while (true) {
new Handler(serverSocket.accept()).start();
}
} catch (IOException e) {
ConsoleHelper.writeMessage("Something wrong, Server socket closed.");
}
}
public static void sendBroadcastMessage(Message message){
for(Connection c : connectionMap.values()){
try {
c.send(message);
} catch (IOException e) {
ConsoleHelper.writeMessage("Message couldn't be sent.");
}
}
}
private static class Handler extends Thread {
private Socket socket;
public Handler(Socket socket){
this.socket = socket;
}
private String serverHandshake(Connection connection)throws Exception{
// String data;
while(true) {
connection.send(new Message(MessageType.NAME_REQUEST));
Message response = connection.receive();
if (response.getType().equals(MessageType.USER_NAME)) {
String data = response.getData();
if (data != null && !(data.isEmpty())) {
if(!(connectionMap.containsKey(data))) {
connectionMap.put(data, connection);
connection.send(new Message(MessageType.NAME_ACCEPTED));
return data;
}
}
}
}
}
public void run(){
String userName = null;
ConsoleHelper.writeMessage("A new connection with "+socket.getRemoteSocketAddress()+" has been established");
try(Connection connection= new Connection(socket)){
userName= serverHandshake(connection);
sendBroadcastMessage(new Message(MessageType.USER_ADDED, userName));
notifyUsers(connection, userName);
serverMainLoop(connection,userName);
}catch(Exception e){
ConsoleHelper.writeMessage("Error while communicating with "+socket.getRemoteSocketAddress());
}finally{
if (userName != null) connectionMap.remove(userName);
sendBroadcastMessage(new Message(MessageType.USER_REMOVED, userName));
}
}
private void notifyUsers(Connection connection, String userName)throws Exception{
for(Map.Entry<String, Connection> map: connectionMap.entrySet()){
if (!map.getKey().equals(userName)){
connection.send(new Message(MessageType.USER_ADDED, map.getKey()));
}
}
}
private void serverMainLoop(Connection connection, String userName)throws Exception{
while(true){
Message receive = connection.receive();
if (receive.getType().equals(MessageType.TEXT)){
String data=userName + ": " + receive.getData();
sendBroadcastMessage(new Message(MessageType.TEXT, data));
}else {
String message =". The message type does not match the protocol.";
ConsoleHelper.writeMessage(message);
}
}
}
}
}