2013-08-01 79 views
1

我正在編寫一個程序,其中客戶端請求服務器的核心數。我這樣做如下:服務器/客戶端通信不工作java

客戶:

public void actionPerformed(ActionEvent e) { 
      try { 
       Socket clientSocket = new Socket("128.59.65.200", 6789); 
       DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 
       BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
       String numberOfCores = inFromServer.readLine();clientSocket.close(); 
       System.out.println(numberOfCores); 
      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 

     } 

    }); 

服務器:

public static void sendNumberOfCores() { 
    Thread coresThread = new Thread() { 
     public void run() { 
      try { 
       int numberOfCores; 
       ServerSocket welcomeSocket = new ServerSocket(6789); 
       while (true) { 
        Socket connectionSocket = welcomeSocket.accept(); 
        DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); 
        numberOfCores = Runtime.getRuntime().availableProcessors(); 
        outToClient.write(numberOfCores); 
       } 

      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 

    }; 
    coresThread.setName("Wait for core request thread"); 
    coresThread.start(); 
} 

然而,當我加載服務器和打在我的GUI按鈕運行於客戶端代碼,沒有任何反應,按鈕只是卡住了。這是什麼造成的?

謝謝。

+0

這是因爲你正在UI線程中運行Socket連接。您將需要爲套接字創建一個新的線程。 –

+0

您已經爲服務器和客戶端放置了相同的代碼。 – Robadob

+0

對不起,我更新了它。 – user760220

回答

0

它結束了我發送一個整數,當客戶端上的代碼正在等待一個字符串。

0
Server not initialized on the 6789 port and make sure you do that in a separate thread. 
Some thing like this. 

In Server class: 
--Make an inner class say MyServer 

    class MyServer implements Runnable{ 
     final int BACKLOG=10; //10 is the backlog,if your server wishes to serve requests. 
     final int PORT = 6789; 
     public void run(){ 
      try { 

         ServerSocket serverSocket = new ServerSocket(PORT,BACKLOG); //10 is the backlog,if your server wishes to serve conncurrent requests. 

       while (true) { 
         Socket ClientConnetion = serverSocket.accept(); 


      //Now whatever you want to do with ClientConnection socket you can call 


       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
} 


--Start this thread in you main server class 

MyServer mys=new MyServer(); 
     Thread r=new Thread(mys); 
     mys.start();