Inputstream Wie schauen, dass etwas in diesen steht?

  • Antworten:3
  • Bentwortet
Sebastian Krüger
  • Forum-Beiträge: 11

14.04.2016, 12:26:14 via Website

Hallo,
Gibt es irgendeine Möglichkeit eine Prozedur auszulösen sobald im Inputstream etwas empfangen wird?

Vielen Dank im Vorraus

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

14.04.2016, 12:30:57 via Website

Direkt geht das nicht.
Ich würde den InputStream in einem eigenen Thread überwachen und in einer While schleife mit available() prüfen ob was da ist.
Wenn ja das was da ist nach der schleife auswerten und dann wieder in die schleife springen wenn fertig verarbeitet

LG Pascal //It's not a bug, it's a feature. :) ;)

Sebastian Krüger

Antworten
Fabian Simon
  • Forum-Beiträge: 359

14.04.2016, 13:05:18 via Website

Also ich mache es so....

/**
 * Stream in und output handler fuer alle geoeffneten verbindungen (Sowohl fuer Client als auch Server)
 * 
 * @author Fasibio
 *
 */
public class ConnectionStream extends Thread implements ICommunikator{

    private InputStream input;
    private OutputStream output;

    private IMessage message;
    private boolean close;
    private static Log log = LogFactory.getLog(ConnectionStream.class);
    /**
     * Standart Konstruktor
     * @param input der {@link InputStream} auf den der Thread nach aufruf von {@link #start()} nach neuen Narichten horcht
     * @param output der {@link OutputStream} an den Narichten verschickt werden
     * @param message die Klasse die den Observer {@link IMessage} realisiert
     */
    public ConnectionStream(InputStream input, OutputStream output, IMessage message){
        this.input = input;
        this.output = output;
        this.message = message;
    }

    @Override
    public void run() {
        super.run();

        while (!close){
            byte[] buffer = new byte[1024];
            boolean end = false;
            String messageString ="";
            try{
                DataInputStream in = new DataInputStream(input);
                int bytes = 0;
                buffer[0] = in.readByte();
                if (buffer[0] == 0){
                    //Normale msg
                    buffer[1] = in.readByte();
                    byte[] msglength = new byte[buffer[1]];
                    int msgbyte = in.read(msglength);
                    String strmsglength = new String(msglength,0,msgbyte);
                    int bytesToRead = Integer.parseInt(strmsglength);
                    while(!end){
                        bytes = in.read(buffer);
                        messageString += new String(buffer,0,bytes);
                        if (messageString.length() == bytesToRead){
                            end = true;
                        }
                    }
    //              messageString = Compressor.decompress(messageString);
                    log.info("New Message read: "+messageString);
                    AbstrTransferParent sendtoClient = message.newMessage(this, new JSON().getObj(messageString));
                    if (sendtoClient!= null){
                        try{
                            write(sendtoClient);    
                        }catch(Exception e){
                            log.error(e);
                        }

                    }
                }else if(buffer[0] == 1){
                    //Stream
                    message.newMusicStream(input);
                } else if (buffer[0] == 2){
                    message.uploadStream(input);
                }
            }catch (Exception e){
                message.exceptionThrow(this, e);
                break;
            }
        }
        message.connectionClosed(this);
    }


    /**
     * Liefert den {@link InputStream} zurueck
     * @return
     */
    public InputStream getInputStream(){
        return input;
    }

    /**
     * Schließt die verbindung
     */
    public void close(){
        this.close = true;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            log.error(e);
        }
        this.stop();
    }

    /**
     * Schieckt einen String an den Client
     * Type : 0
     * @param call 
     */
    public void write(AbstrTransferParent call){
        String json = new JSON().getJson(call);
        try {
            log.info("Write: "+json);

            //json = Compressor.compress(json);
            byte typ = 0;
            byte[] msglength = (""+json.length()).getBytes() ;
            byte length = Byte.parseByte(msglength.length+"");
            byte[] toSend = new byte[json.getBytes().length+msglength.length+2];
            toSend[0] = typ;
            toSend[1] = length;
            int v = 0;
            for (int i = 2; i < msglength.length+2;i++){
                toSend[i] = msglength[v];
                v++;
            }

            v = 0;
            for(int i = msglength.length+2; i < toSend.length;i++){
                toSend[i] = json.getBytes()[v];
                v++;
            }
            log.debug("Nach Byteumwandlung: "+new String(toSend));
            output.write(toSend);
            output.flush();
        } catch (IOException e) {
            log.error(e);
        }
    }

    /**
     * Um einen anderen {@link InputStream} ueber den {@link OutputStream} zu versenden
     * Type : 2 
     * @param stream
     */
    public void uploadStream(InputStream stream){
        byte typ = 2;
        try {
            output.write(typ);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                log.error(e);
            }
            IOUtils.copy(stream, output);
        } catch (IOException e) {
            log.fatal(e);
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            log.error(e);
        }
    }

    /**
     * Um einen {@link InputStream} an den {@link OutputStream} zusenden mit dem Grund diesen direkt auf dem gegenpartner zu verwenden
     * @param stream
     */
    public void writeStream(InputStream stream){
        byte typ = 1;
        try {
            output.write(typ);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                log.error(e);
            }
            IOUtils.copy(stream, output);
        } catch (IOException e) {
            log.fatal(e);
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            log.error(e);
        }
    }

    @Override
    public String getCommunikatorName() {
        return "Connection Stream";
    }

}

Is jetzt halt meine Komplette Read und Write klasse für ein ganz speziellen Anwendungsfall...

Aber Vielleicht hilft es dir ja...

Sebastian Krüger

Antworten
Sebastian Krüger
  • Forum-Beiträge: 11

14.04.2016, 17:44:24 via Website

Danke ich glaube ich kriege das jetzt hin :D

Antworten