Originariamente inviato da java_junior87
Ho dovuto modificare un codice che implementava una semplice chat: ho aggiunto l'hashmap per avere una mappatura tra utente che si aggiunge e la porta da cui invia messaggi. Il problema è che non riesco ad inviare i messaggi di un cliente in broadcast, vorrei che quando un utente invia un messaggio questo venga letto da tutti. Ma non funziona!!!

Per favore qualcuno può darmi una mano?

Posto il codice del server:

codice:
class ChatServerProtocol {
    private String nick;
    private ClientConn conn;
    public ChatServer server;
    
    ...

    
    public ChatServerProtocol(ClientConn c) {
        nick = null;
        conn = c;
    }
    

    ...

    /** Process a message coming from the client sending it to all the connected clients */
    public String process(String msg) {
        if (!isAuthenticated()) 
            return authenticate(msg);

//         String[] msg_parts = msg.split(" ", 1);
// 
//             if(sendMsg(msg_parts[0]/*, msg_parts[1]*/)) return msg_OK;
//             else return msg_SEND_FAILED;

      server.broadcast(msg);
      return msg_OK;

   }
}

class ClientConn implements Runnable {
    private Socket client;
    private BufferedReader in = null;
    public PrintWriter out = null;

    ClientConn(Socket client) {
        this.client = client;
        try {
            /* obtain an input stream to this client ... */
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            /* ... and an output stream to the same client */
            out = new PrintWriter(client.getOutputStream(), true);
        } catch (IOException e) {
            System.err.println(e);
            return;
        }
    }

    public void run() {
        String msg, response;
        ChatServerProtocol protocol = new ChatServerProtocol(this);
        try {
            /* loop reading lines from the client which are processed 
             * according to our protocol and the resulting response is 
             * sent back to the client */
            while ((msg = in.readLine()) != null) {
                response = protocol.process(msg);
                out.println("SERVER: " + response);
            }
        } catch (IOException e) {
            System.err.println(e);
        }
    }

    public void sendMsg(String msg) {
        out.println(msg);
    }
}
Nella classe ChatServerProtocol non istanzi ChatServer (di cui hai un campo di esemplare nominato server), quindi nel momenti in cui viene invocato protocol.process(msg), in esso viene sollevata una NullPointerException per via del fatto che server è nullo.