2012-02-09 36 views
0

請原諒我的寫入錯誤... 我使用NetBeans運行自制服務器和客戶端,並且一切正常。正如我之前所說的,我在客戶端使用「套接字」,在我的客戶端使用「ServerSocket」。我也在服務器中使用JDBC Mysql。 當我在它們的可分發文件夾中生成兩個java文件並使用它們時,問題就開始了。客戶端向服務器發送信息(它以.getOutputStream()和.getInputStream()開頭,然後是.flush()),但服務器沒有收到任何消息。我想看到它停止,它在我的服務器在讀取.accept()時停止工作,使用套接字

客戶[I] =新的客戶端(服務器接受(),我。);

當我嘗試從NetBeans和客戶端從我的桌面執行我的服務器時,會發生瘋狂的事情......它的工作原理!所以服務器一定是問題。我也使用一個打開的UDP端口,並且正在尋找192.168.0.10(這是我的電腦,在局域網中)服務器的IP。

我希望有人能幫助我,在此先感謝!


在這裏,我貼我的代碼,我很抱歉有些變量是在西班牙:

公共ServidorMultiCliente(){ 超( 「Servidor MultiCliente」); initComponents();

try{ 
     servidor = new ServerSocket(500, maxNumberClients); 
    }catch(IOException excepcion){ 
     excepcion.printStackTrace(); 
     System.exit(1); 
    } 

    serverWriteBox.append("Server iniciated, waiting for connections..."); } 

我運行這些,從服務器:

公共無效ejecutar(){ clientsAcceptor.start(); messagesListener.start(); }

其中clientsAcceptor是:

私有類aceptadorClientes繼承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做了同樣的事情,這是每個新客戶端的新線程。它在一個循環中,一直在聽。在這裏,我貼我的可執行的客戶端,這是我用在ServidorMultiCliente的Cliente類不同:

公共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(); 
    } 
} 

私人無效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 
} 

回答

1

ServerSocket#accept是阻塞呼叫。它監聽端口並在客戶端連接時返回Socket。你不會展示你的服務器邏輯,但你似乎把客戶端放在一個數組中,所以你顯然想要支持多個客戶端。你不會顯示你的Client類是否啓動線程並立即返回。

您應該有一個服務器環路,它只監聽服務器套接字,並在之後創建客戶端它檢索到客戶端套接字。即使你在你的Client構造函數中做了這個(我沒有代碼也不知道),它不是一個很好的地方,並嚴重妨礙了調試。

如果你不爲客戶啓動線程,這將解釋一個「停止」的服務器(如果「停止」意味着「塊」而不是「崩潰」)。有關詳細說明,請參見"Writing the Server Side of a Socket" in the Java Tutorial

我想不出爲什麼它通過Netbeans啓動時表現不同。需要更多的代碼上下文。

+0

是的,我想我應該粘貼我的代碼...它來了: – Dungoo0 2012-02-09 15:00:51

相關問題