[英]how to accept only 1 connection in socket
嗨,我有服务器的这段代码,我添加了if以检查ocupado(busy)是否为0,接受套接字,如果其open busy为1,所以拒绝,直到第一个用户完成连接,但不起作用...
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 {
}
}
}
所以我的问题是如何使套接字每次仅接受一个连接,并且当用户在确认框中按“确定”时,服务器关闭连接。
我将添加,我的问题是“逻辑”或命令仅允许一个连接,当客户端尝试时,它拒绝连接,稍后我将在客户端中处理被拒绝的连接
根据JavaDocs for ServerSocket ,您可以将backlog设置为第二个参数。 如果请求超过此积压,则将被拒绝。 按照这一行:
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
因此,您可以尝试以下操作:
ServerSocket servidor = new ServerSocket(9000, 1);
通过使用单线程服务器,您已经在确保这一点。 在完成之前的客户端之前,您无法返回到accept()
调用。 完全不需要您的occupado
测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.