2012-07-13 79 views
3

客戶端發送數據到服務器時出現問題。當我從服務器發送數據到客戶端時,一切都很好。我收到了這條消息:「客戶端接收:消息」,但當我發送「客戶端消息」時,我的服務器沒有收到它。客戶端 - 服務器應用程序JAVA,服務器不接收數據

import java.io.IOException; 

import java.net.*; 
import java.io.*; 

public class Server {  
    public static void main(String[] args) throws IOException { 

     ServerSocket serverSocket = null; 
     try { 
      serverSocket = new ServerSocket(4444); 
     } catch (IOException e) { 
      System.err.println("Could not listen on port: 4444."); 
      System.exit(1); 
     } 

     Socket clientSocket = null; 
     try { 
      clientSocket = serverSocket.accept(); 
     } catch (IOException e) { 
      System.err.println("Accept failed."); 
      System.exit(1); 
     } 

     PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); 
     BufferedReader in = new BufferedReader(
           new InputStreamReader(
           clientSocket.getInputStream())); 
     String inputLine, outputLine; 

     outputLine = "message"; 
     out.println(outputLine); 

     while ((inputLine = in.readLine()) != null) { 
      System.out.println("server receive: " + inputLine); 
      outputLine = "second message"; 
      out.println(outputLine); 
     } 

     out.close(); 
     in.close(); 
     clientSocket.close(); 
     serverSocket.close(); 
    } 
} 


public void actionPerformed(ActionEvent e) { 

    if (e.getSource() == startButton) { 
     this.main.getContentPane().remove(homePanel); 
     String name = this.name.getText(); 

     String result;    
     try { 
      connectionToServer(); 
      if ((result = in.readLine()) != null) { 
       System.out.println("client receive: " + result); 
       out.println("client's message"); 
      } 
     } catch(IOException err) { 
      System.out.println("error"); 
     } 

    }   
} 

public void connectionToServer() throws IOException { 
    try { 
     this.socket = new Socket("localhost", 4444); 
     this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); 
     this.out = new PrintWriter(this.socket.getOutputStream(), true); 
    } catch (IOException e) { 
     System.err.println("Couldn't get I/O for the connection to: taranis."); 
     System.exit(1); 
    }   
} 
+2

比較你的方法這個工作[示例](http://stackoverflow.com/a/3245805/230513)。 – trashgod 2012-07-13 19:38:21

+1

問題可能出現在客戶端代碼中,這裏還有一個相關的[示例](http://stackoverflow.com/a/9240450/1057230)。希望你不要阻塞你的'Event Dispatch Thread'! – 2012-07-14 16:49:22

+2

如果可能,您應該發佈客戶端代碼。 – JeanValjean 2012-09-20 12:59:02

回答

1

你的actionPerformed方法只是連接服務器,什麼都不做。

服務器在發送消息後關閉。

手錶:而(!(inputLine = in.readLine())= NULL)

如果客戶端不發送任何消息,代碼將打破,那麼你就關閉了服務器。

相關問題