Java: Sending messages over the network repeatedly in another thread?

Asked

Viewed 46 times

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 starts when the message "This is a test" only appears once, and then no longer appears, someone can help me?

1 answer

1


The first step is to capture the Exception that your code may be generating in this loop infinite that you did in this Thread.

This code fires at full speed this message because there is no waiting time between a transmission and another. So, initially print the Exception with a e. printStackTrace() , This will let you know what’s going on.

As it is a continuous activity task, use a rational waiting time between a shot and another with the Thread.Sleep(3000) (in this example the code waits three seconds when reading this line).

In your conditional expression try to use a variable that can change status to close the 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
}
}

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.