简体   繁体   中英

how to accept only 1 connection in socket

Hi i have this code of the server and i added the if to check if ocupado(busy) is = 0, accept socket, if its open busy = 1, so reject till the first user finish the connection, but dont work...

import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 *
 * @author www
 */
public class ServidorTCPBasico {
static int ocupado = 0; // = busy var to check
  public static void main(String[] args) {

    try {

      // Instancia o ServerSocket ouvindo a porta 9000

      ServerSocket servidor = new ServerSocket(9000);

      System.out.println("Servidor ouvindo a porta 9000");

      while(true) {

        // o método accept() bloqueia a execução até que

        // o servidor receba um pedido de conexão
        Socket cliente = servidor.accept();
        if(ocupado == 0) { 

        int ocupado = 1;
        System.out.println("Cliente conectado: " + cliente.getInetAddress().getHostAddress());
System.out.println(ocupado);
        ObjectOutputStream saida = new ObjectOutputStream(cliente.getOutputStream());

        saida.flush();

//        saida.writeObject(new Date());
        saida.writeUTF("TEXTO TESTE PARA TRANSFERIR...");
        saida.close();

      //  cliente.close();

        }  else { 
            System.out.println("Ocupado");
          }

      }   
    }


    catch(Exception e) {

       System.out.println("Erro: " + e.getMessage());

    } 

    finally {
    }  


  }     

}

so my question is how to make the socket to accept onnly one connection per time, and THE SERVER close the connection when the user press OK in a confirm box..

the part of confirm box etc.. i will add, my problem is the "logic" or command to allow only one connection, when the client try, it refuse the connection, i will treat the refused connection in the client later

As per the JavaDocs for ServerSocket , you can set a backlog as the 2nd parameter. If requests exceed this backlog they are simply refused. As per this line:

The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection indication arrives when the queue is full, the connection is refused

So, you can try the following:

ServerSocket servidor = new ServerSocket(9000, 1);

You're already ensuring that, by having a single-threaded server. You can't get back to the accept() call until you've finished with the previous client. There is no need for your occupado test at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM