Hello beautiful people!
I'm trying to understand Socket Programming. I'm implementing a basic chat with 2 users. I've been following a tutorial: https://www.youtube.com/watch?v=AUpytdHcwUg and I'm changing some parts during the path but I'm not still satisfied.
To avoid multiple if/else I implemented a Factory Class, so that according to the first word (Cmd) that the client (ServerWorker) types in the console, the Factory Class is able to understand what to do. "Login XXXXXXXXX" -> will call the HandleLogin method. "Msg XXXXXXXXXXX" -> will call the HandleMessage method.
I created a
public interface CmdExecutor {
void execute(String[] tokens, OutputStream outputStream, List<ServerWorker> serverWorkers) throws IOException;
}
and a Factory Class:
public Map<String, CmdExecutor> cmdMap = new HashMap<>();
{
cmdMap.put("login",new HandleLogin());
cmdMap.put("logout",new HandleLogout());
}
public CmdExecutor getExecutor(String line){
String[] tokens = StringUtils.split(line);
return cmdMap.get(tokens[0]);
}
}
Now: When i Login for example, I have to let the other clients (ServerWorkers) know that I've just logged-in, and I'd like to follow the Single Responsability Principle. I don't want my interface to do many jobs. So I don't want to pass in even the ServerWorker parameter but I'd like to know if there's some event listener pattern, or another pattern (i don't know!) to perform an action after the HandleLogin or other method is called.
Please help me make my code cleaner! I hope I made myself clear enough to understand the situation...
public void handleClientSocket() throws IOException {
InputStream inputStream = clientSocket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
clientSocket.getOutputStream().write("Type something or 'logout' to exit: ".getBytes());
while ((line = bufferedReader.readLine()) != null) {
String[] tokens = StringUtils.split(line);
if(tokens[0].equalsIgnoreCase("logout")) {
}
workerFactory.getExecutor(line).execute(tokens,outputStream, server.getServerWorkers());
clientSocket.close();
}
}
}
This is what happens at the very beginning in my client/ServerWorker instance.
Aucun commentaire:
Enregistrer un commentaire