1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package fr.insa.clavardator.server;
-
- import fr.insa.clavardator.lib.errors.UsernameTakenException;
- import fr.insa.clavardator.lib.message.Message;
- import fr.insa.clavardator.lib.network.TcpConnection;
- import fr.insa.clavardator.lib.network.TcpListener;
- import fr.insa.clavardator.lib.users.UserInformation;
- import fr.insa.clavardator.lib.util.Log;
-
- import java.io.EOFException;
- import java.io.Serializable;
- import java.util.HashMap;
- import java.util.Map;
-
- public class Proxy {
- private static final int PROXY_PORT = 35750;
- private final HashMap<String, TcpConnection> users = new HashMap<>();
- private final TcpListener proxyListener;
-
- public Proxy() {
- proxyListener = new TcpListener(PROXY_PORT);
- proxyListener.acceptConnection(clientSocket -> {
-
- Log.v(getClass().getSimpleName(), "Accepting a new user");
- TcpConnection connection = new TcpConnection(clientSocket);
- connection.receive(msg -> {
-
- if (msg instanceof Message) {
- Log.v(getClass().getSimpleName(), "Transmitting message: " + msg);
- transmitMessage((Serializable) msg, ((Message) msg).getRecipient().id);
-
- } else if (msg instanceof UsernameTakenException) {
- UsernameTakenException unameTaken = ((UsernameTakenException) msg);
- transmitMessage(unameTaken, unameTaken.recipient);
-
- } else if (msg instanceof UserInformation) {
- Log.v(getClass().getSimpleName(), "Registering new user: " + msg);
- users.put(((UserInformation) msg).id, connection);
- for (String userId : users.keySet()) {
- UserInformation userInfo = ((UserInformation) msg);
- if (!userId.equals(userInfo.id)) {
- transmitMessage((Serializable) msg, userId);
- }
- }
- }
-
- }, e -> {
- if (e instanceof EOFException) {
- for (Map.Entry<String, TcpConnection> user : users.entrySet()) {
- if (user.getValue().equals(connection)) {
- Log.v(getClass().getSimpleName(), "Disconnecting user " + user.getKey());
- users.remove(user.getKey());
- break;
- }
- }
- } else {
- Log.e(getClass().getSimpleName(), "Error while receiving message to transmit", e);
- }
- });
- },
- e -> Log.e(getClass().getSimpleName(), "Error while accepting a user", e));
- }
-
-
- void transmitMessage(Serializable msg, String recipientId) {
- TcpConnection user = users.get(recipientId);
- if (user == null) {
- Log.e(getClass().getSimpleName(), "Cannot find the recipient in the connected users");
- } else {
- user.send(msg, null, e -> Log.e(getClass().getSimpleName(), "Error while sending message", e));
- }
- }
-
- public void stop() {
- proxyListener.stopAccepting();
- for (TcpConnection connection : users.values()) {
- connection.close();
- }
- }
- }
|