Java server disconnects idle users after 5 minutes

Asked

Viewed 567 times

3

I’m using this Java methodology for connection between client and server, I copied it from the internet, and it helped me a lot, but the server allows the user to stay connected while he’s sending messages, but if the user stays an average time of 5 minutes without sending anything it is disconnected.
How to increase this time to about 30 minutes or disable this inactivity disconnection?

Settings:
Netbeans 8.0
Windows Seven Ultimante 64 Bits

Follows the code :

package redes;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatCliente extends JFrame {  

    JTextField textoParaEnviar;
    PrintWriter escritor;
    Socket socket;
    String nome;
    JTextArea textoRecebido;
    Scanner leitor;


    private class EscutaServidor implements Runnable{

        public void run() {
            try{
                String texto;
                while((texto=leitor.nextLine()) != null){
                    textoRecebido.append(texto+"\n");
                }
            }catch(Exception x){}
        }
    }

    public ChatCliente(){

        super("Chat");
        Font fonte = new Font("Sefif", Font.PLAIN,26);
        textoParaEnviar = new JTextField();
        textoParaEnviar.setFont(fonte);
        JButton botao = new JButton("Enviar");
        botao.setFont(fonte);
        botao.addActionListener(new EnviarListener());

        Container envio = new JPanel();
        envio.setLayout(new BorderLayout());
        envio.add(BorderLayout.CENTER, textoParaEnviar);
        envio.add(BorderLayout.EAST, botao);
        getContentPane().add(BorderLayout.SOUTH,envio);

        textoRecebido= new JTextArea();
        textoRecebido.setFont(fonte);
        JScrollPane scroll= new JScrollPane(textoRecebido);
        getContentPane().add(BorderLayout.CENTER, scroll);

        configurarRede();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500,500);
        setVisible(true);
    }

    private class EnviarListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            escritor.println(nome+" : "+textoParaEnviar.getText());
            escritor.flush();
            textoParaEnviar.setText("");
            textoParaEnviar.requestFocus();
        }
    }

    private void configurarRede(){
        try{
            socket = new Socket("127.0.0.1",5000);
            escritor = new PrintWriter(socket.getOutputStream());
            leitor=new Scanner(socket.getInputStream());
            new Thread(new EscutaServidor()).start();
        }catch(Exception e){}
    }

    public static void main(String[] args) {
        new ChatCliente();
    }

}

package redes;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ChatServer {
    List<PrintWriter> escritores =  new ArrayList<>();

    public ChatServer(){

        class EscutaCliente implements Runnable{

            Scanner leitor;
            public EscutaCliente(Socket socket){
                try{
                    leitor =  new Scanner (socket.getInputStream());
                }catch(Exception e){

                }
            }


            void encaminharParaTodos(String texto){
                for(PrintWriter w: escritores){
                    try{
                        w.println(texto);
                        w.flush();
                    } catch(Exception x){}
                }
            }


            public void run() {
                try{
                    String texto;
                    while((texto=leitor.nextLine()) != null){
                        System.out.println(texto);
                        encaminharParaTodos(texto);
                    }
                }catch(Exception x){}
            }
        }

        ServerSocket server;
        try {
            server = new ServerSocket(5000);
            while(true){
                Socket socket = server.accept();
                new Thread(new EscutaCliente(socket)).start();
                PrintWriter p = new PrintWriter(socket.getOutputStream());
                escritores.add(p);
            }

        } catch (IOException e) {}
    }

    public static void main(String[] args) {
        ChatServer c= new ChatServer();
    }
}

package redes;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ConselhoCliente {

    /**
     * @param args
     * @throws IOException 
     * @throws UnknownHostException 
     */
     public static void main(String[] args) throws UnknownHostException, IOException {
        //Socket conexão de rede
         Socket socket = new Socket("127.0.0.1",5000); 
         Scanner s = new Scanner (socket.getInputStream());
         System.out.println("Mensagem"+s.nextLine());
         s.close();

     }

}

package redes;

import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ConselhoServidor {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        ServerSocket server = new ServerSocket(5000);

        //aguarda chegada de novos clientes
        while(true){
            Socket socket=server.accept();
            try (PrintWriter w = new PrintWriter(socket.getOutputStream())){
                w.println("Aprenda Java");
            }
        }
    }

}

2 answers

3


2

In addition to defining the timeout, as already explained by Paulo’s reply, it is interesting to implement a mechanism to automatically reconnect the user in case of oscillation of the Internet connection.

The problem is that defining a timeout is not enough to ensure that the user will not be disconnected. If its Internet fails even if for a few seconds another network error will occur.

Think of something like:

timeout = 0 //tempo infinito
while (!terminarPrograma) {

    socket = conectar()
    socket.setSoTimeout(timeout)
    aguardarSocketTerminar() 

}

Browser other questions tagged

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