请原谅我的写作错误... 我正在使用 NetBeans 运行自制服务器和客户端,一切正常。正如我之前所说,我在客户端上使用“Socket”,在 sv 上使用“ServerSocket”。我还在服务器中使用 JDBC Mysql。 当我在其可分发文件夹中生成两个 java 文件并使用它们时,问题就开始了。客户端向服务器发送信息(以 .getOutputStream() 和 .getInputStream() 开头,然后是 .flush() ),但服务器没有收到任何消息。我试着看看它停在哪里,它在
clients[i] = new Client (server.accept(), i);
当我尝试从 NetBeans 执行服务器并从桌面执行客户端时,疯狂的事情发生了......它有效!所以肯定是服务器的问题。我还使用开放的 UDP 端口,并且正在查找 192.168.0.10 上服务器的 IP(这是我的计算机,在 LAN 中)。
希望有人能帮助我,先谢谢了!
<小时/>在这里我粘贴我的代码,很抱歉有些变量是西类牙语:
public ServidorMultiCliente() { super("Servidor MultiCliente"); initComponents();
try{ servidor = new ServerSocket( 500, maxNumberClients); }catch(IOException excepcion){ excepcion.printStackTrace(); System.exit(1); } serverWriteBox.append("Server iniciated, waiting for connections..."); }
我从服务器运行这些:
public void ejecutar(){ clientsAcceptor.start(); messagesListener.start(); }
clientAcceptor 所在位置:
private class aceptadorClientes extends Thread{
public void run(){ for( int i = 1; i < maxNumberClients; i++ ){ try{ clientes[i] = new Cliente (servidor.accept(), i); // **Here it stops** // It never reaches here... (without using NetBeans) clientes[i].start(); clientes[i].aceptado = true; }catch(IOException excepcion){ excepcion.printStackTrace(); } }
这就是我在不同线程中接受客户端的方式。我用 messageListener 做了同样的事情,它是每个新客户端的新线程。它处于循环状态,始终在聆听。在这里,我粘贴了可执行的 Client,它与我在 ServidorMultiCliente 中使用的 Cliente 类不同:
public Cliente(){ }
public Cliente(String host){ this.host = host; this.executeConnection(); } public void executeConnection(){ int connect = 0; try { cliente = new Socket(InetAddress.getByName(host), 500); conectar = 1; } catch (IOException ex) { conectar = 0; this.ejecutarConexion(); } if(conectar == 1){ obtainFlows(); } }
private void obtainFlows(){
try{ output= new ObjectOutputStream( cliente.getOutputStream()); output.flush(); // Here I should be "connected" input = new ObjectInputStream(cliente.getInputStream()); } catch(IOException ex){ this.initiateDisconnection(); } sendFlows("I'm connected!"); new messageListener().start(); // This is a thread }
最佳答案
ServerSocket#accept
是阻塞调用。它监听端口并在客户端连接时返回Socket
。您没有显示太多服务器逻辑,但似乎您将客户端放入一个数组中,因此您显然希望支持多个客户端。您不会显示您的 Client
类是否启动线程并立即返回。
您应该有一个服务器循环,它仅监听服务器套接字并在检索客户端套接字后创建客户端。即使您在 Client
构造函数中执行此操作(如果没有代码我也无法判断),这也不是一个很好的地方,并且会严重阻碍调试。
如果您不为客户端启动线程,这将解释服务器“停止”(如果“停止”意味着“阻塞”而不是“崩溃”)。请参阅"Writing the Server Side of a Socket" in the Java Tutorial详细解释。
我不明白为什么它在通过 Netbeans 启动时表现不同。需要更多的代码上下文。
关于java - 使用套接字读取 .accept() 时,我的服务器停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9212044/