Chat-Applikation/src/server/ClientPushMessageThread.java

79 lines
3.2 KiB
Java

/*
* Copyright (C) 2021 eichehome
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import utils.Message;
/**
* Diese Klasse stellt einen Thread dar, die Nachrichten, die er in einem Stream erhällt an einen Client weiterleitet.
*
* @author eichehome
*/
public class ClientPushMessageThread extends Thread {
private final ObjectOutputStream out;
private final ObjectInputStream pipedObjectInputStream;
private ClientStore clientStore;
/**
* Haupt methode der Threads, in der alles abläuft.
*/
public void run() {
boolean continueLoop = true;
while (continueLoop) {
try {
Message empfangen = null;
while ((empfangen = (Message) this.pipedObjectInputStream.readObject()) != null) {
this.out.writeObject(empfangen);
this.out.flush();
Logger.getLogger(ClientPushMessageThread.class.getName()).log(Level.INFO, String.format("Pushing Thread %d: Nachricht weitergegeben", this.getId()));
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(ClientPushMessageThread.class.getName()).log(Level.SEVERE, String.format("Pushing Thread %d: Fehler: %s", this.getId(), ex));
} catch (EOFException ex) {
Logger.getLogger(ClientPushMessageThread.class.getName()).log(Level.SEVERE, String.format("Pushing Thread %d: Fehler: %s", this.getId(), ex));
continueLoop = false;
clientStore.close(this);
clientStore.removeClient(this);
} catch (IOException ex) {
Logger.getLogger(ClientPushMessageThread.class.getName()).log(Level.INFO, String.format("Pushing Thread %d: Pipe wurde beendet", this.getId()));
clientStore.removeClient(this);
continueLoop = false;
}
}
}
/**
* Konstruktor
* @param out Stream, in dem der Thread die Nachrichten an den Client schickt.
* @param pipedObjectInputStream Stream, in dem der Thread die Nachrichten von anderen Threads erhält.
* @param clientStore Zeiger auf das zentrale Verzeichnis der Clients, um sich dort austragen zu können.
*/
public ClientPushMessageThread(ObjectOutputStream out, ObjectInputStream pipedObjectInputStream, ClientStore clientStore) {
this.out = out;
this.pipedObjectInputStream = pipedObjectInputStream;
this.clientStore = clientStore;
}
}