Java: Send message on the network repeatedly in another thread?

0

This is my problem: I need a message to be sent by a socket repeatedly, to do this, I created another Thread, so that the application would not be locked, so:

new Thread(new Runnable(){
    public void run(){
        try{
            Socket s = new Socket("127.0.0.1",12739);
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            while(true){
                s.writeUTF("Isso é um teste");
                s.flush();
            }
        } catch(IOException e){}
    }
});

The problem begins when the message "This is a test" appears only once, and then does not appear any more, can someone help me?

    
asked by anonymous 23.02.2017 / 00:59

1 answer

1

The first step is to capture the Exception that your code might be generating in this loop infinite loop / p>

This code fires this message at full speed because it has no waiting time between one transmission and another. So, initially print Exception with a e.printStackTrace () , this will let you know what is happening.

Because it is a continuous activity task, use a rational wait time between one shot and another with Thread.sleep (3000) (in this example the code waits three seconds when you read this line) .

In your conditional expression, try to use a variable that can change state to quit Thread instead of an infinitely true expression.

new Thread(new Runnable(){
public void run(){
    try{
        Socket s = new Socket("127.0.0.1",12739);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        while(true){// mude a expressão eterna por uma variável que possa retornar outro valor, para uma possível parada mais natural da Thread

            s.writeUTF("Isso é um teste");
            s.flush();
    Thread.sleep(3000L); // espera 3 segundos entre cada disparo
        }
    } catch(IOException e){
    e.printStackTrace();// sempre trate as Exceptions que seu programa possa disparar
    dos.close(); // sempre feche os fluxos em caso de erro, principalmente se os erros não fecham sua aplicação
}
}

});

    
24.02.2017 / 03:55