2015-10-29 137 views
2

我在玩一個簡單的ClientServer應用程序使用套接字,我試圖在控制檯打印一條消息,並得到服務器的響應,但什麼也沒有顯示出來,我對套接字相當陌生所以我認爲我有一個邏輯錯誤。這是一個簡單的應用程序,我希望客戶端提示用戶一個命令(在我的情況下,輸入字符串,服務器將執行基於'th字符的操作),將其發送到服務器,並顯示服務器響應。我很確定我的客戶端不正確,有人能指出我爲什麼不能從客戶端控制檯寫入任何東西。java套接字編程聊天

package socketProgramming; 
     import java.io.*; 
     import java.net.*; 

public class MyClient { 

     @SuppressWarnings("resource") 
     public static void main(String[] args) { 
      // TODO Auto-generated method stub 
      Socket socket= new Socket(); 
      BufferedReader in = null; 
      String msg; 
      int port = 2222; 

      try { 

       System.out.println("CLient wants to connect on port: "+port); 

       socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port); 
       System.out.println("The client is connected"); 
      } catch (UnknownHostException e) { 
         System.exit(1); 
      } catch (IOException e) { 
        System.out.println("connect failed"); 
         System.exit(1); 
      } 

      try{ 
       BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
        PrintStream output = new PrintStream(socket.getOutputStream()); 
        String text = null; 
      output.print(text); 

      while ((text = input.readLine()) != null){ 
       System.out.println("Client "+text); 

      } 


       socket.close(); 
       System.out.println("Client Exiting"); 
      } 
      catch(IOException e) { 
       System.out.println(e); 
      }} 


     } 

package socketProgramming; 

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



public class MyServer { 

    public static void main(String[] args) throws IOException { 
     // TODO Auto-generated method stub 

     String msg = ""; 
     ServerSocket sSocket = null; 
     Socket clientSocket; 
     int port = 2222;//Integer.parseInt(args[0]); 
     try{ 
      sSocket = new ServerSocket(port); 

     } catch(IOException e){ 
      System.out.println(e); 
     } 

     while(true){ 
      try {// listen for a connection from client and accept it. 
       System.out.println("Server is listenning on host: " 
         +InetAddress.getLocalHost().getHostAddress() +"" 
           + " and on port: "     
           + port); 

       clientSocket = sSocket.accept(); 
       System.out.println("Connection accepted"); 
       BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 

       // PrintWriter out = 
         // new PrintWriter(clientSocket.getOutputStream(), true); 

       PrintStream output = new PrintStream(clientSocket.getOutputStream()); 

       msg = input.readLine(); 
       if(msg != null){ 
        if(msg.charAt(12)=='4'){ 

         System.out.println("reading message "+msg+" "); 
         output.print("Bye"); 
         sSocket.close(); 
         System.out.println("Server exits"); 
        }else{ 
         if(msg.charAt(12)=='0'){ 

          System.out.println("reading message "+msg+" "); 
          output.print("OK"); 
         }else if (msg.charAt(12)=='1'){ 

          System.out.println("reading message "+msg+" "); 

          //Should return IP address 
          output.print(clientSocket.getInetAddress()); 
         }else if (msg.charAt(12)=='2'){ 

          System.out.println("reading message "+msg+" "); 
          for(int i = 1; i<=10; ++i){ 

           output.print(i); 
           output.print(" "); 
           } 

          }else if (msg.charAt(12)=='3'){ 


           System.out.println("reading message "+msg+" "); 
           output.print("GOT IT"); 


          }else{ 
           System.out.println("*******************"); 
          } 

         } 



        } 
        sSocket.close(); 
        System.out.println("Server exits"); 
       } 



      catch(IOException e) { 
       System.out.println("accept failed"); 
       System.exit(1); 
      } 

     System.out.println("Hello world"); 
    } 


    } 
    } 
+0

你能詳細說明誰是想要開始的消息,以及如何? – Linus

+0

如果他的客戶發送類似'CCCCCCCC type0 4567322 X'的東西,因爲'12th'字符是0 print'Bye'或任何東西。希望它更清楚一點 – Bobby

+0

嗯,我相信我找到了套接字問題的答案。你可能仍然有問題,因爲打印一個'null'字符串會產生一個''null''字符串,但是希望你能診斷任何進一步的問題。 – Linus

回答

2

我花了一些自由度與你的代碼,並改變了一下。它絕不是你所提供的完美版本;但是,它應該讓你指出正確的方向。這些都被解決了的問題:

  • MyClient從來沒有提示用戶輸入。
  • MyServer正在發送沒有換行符的字符串。 MyClient期待帶有換行符的字符串。
  • 在MyServer中,主套接字在循環底部被關閉。我相信你打算關閉客戶端套接字,以便服務器將循環並處理另一個客戶端。
  • 在MyServer中,您正在檢查用戶輸入的第13個字符(因爲您正在爲字符串的第12個字節(從零開始)編制索引,所以我使用強制保護來檢查字符串的第13個字節短。
  • 再次,我只是糾正一些問題在你的代碼。我可能已經改變了它超出了你的真正目標其實是這些例子的目的是讓你去對你的方式...

MyClient .java:

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

public class MyClient { 

    @SuppressWarnings("resource") 
    public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Socket socket = new Socket(); 
    int port = 2222; 

    try { 

     System.out.println("CLient wants to connect on port: " + port); 

     socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port); 
     System.out.println("The client is connected"); 
    } catch (UnknownHostException e) { 
     System.exit(1); 
    } catch (IOException e) { 
     System.out.println("connect failed"); 
     System.exit(1); 
    } 

    try { 
     BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
     PrintStream output = new PrintStream(socket.getOutputStream()); 

     // Get a line of input from the user. 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     String inputFromUser = br.readLine(); 

     // Send that line of input to MyServer. 
     output.println(inputFromUser); 

     // Print out the response from MyServer. 
     System.out.println("SERVER RESPONSE: " + input.readLine()); 

     socket.close(); 
     System.out.println("Client Exiting"); 
    } catch (IOException e) { 
     System.out.println(e); 
    } 
    } 

} 

MyServer.java:

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

public class MyServer { 

    public static void main(String[] args) throws IOException { 
    // TODO Auto-generated method stub 

    String msg = ""; 
    ServerSocket sSocket = null; 
    Socket clientSocket; 
    int port = 2222;// Integer.parseInt(args[0]); 
    try { 
     sSocket = new ServerSocket(port); 

    } catch (IOException e) { 
     System.out.println(e); 
    } 

    while (true) { 
     try {// listen for a connection from client and accept it. 
     System.out.println("Server is listenning on host: " + InetAddress.getLocalHost().getHostAddress() + "" + " and on port: " 
      + port); 

     clientSocket = sSocket.accept(); 
     System.out.println("Connection accepted"); 
     BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 

     // PrintWriter out = 
     // new PrintWriter(clientSocket.getOutputStream(), true); 

     PrintStream output = new PrintStream(clientSocket.getOutputStream()); 

     msg = input.readLine(); 
     if (msg != null) { 
      if (msg.length() > 12 && msg.charAt(12) == '4') { 

      System.out.println("reading message " + msg + " "); 
      output.println("Bye"); 
      System.out.println("Server exits"); 
      } else { 
      if (msg.length() > 12 && msg.charAt(12) == '0') { 

       System.out.println("reading message " + msg + " "); 
       output.println("OK"); 
      } else if (msg.length() > 12 && msg.charAt(12) == '1') { 

       System.out.println("reading message " + msg + " "); 

       // Should return IP address 
       output.println(clientSocket.getInetAddress()); 
      } else if (msg.length() > 12 && msg.charAt(12) == '2') { 

       System.out.println("reading message " + msg + " "); 
       for (int i = 1; i <= 10; ++i) { 

       output.println(i + " "); 
       } 

      } else if (msg.length() > 12 && msg.charAt(12) == '3') { 

       System.out.println("reading message " + msg + " "); 
       output.println("GOT IT"); 

      } else { 
       System.out.println("*******************"); 

       // Invalid question from client, I guess. 
       output.println("HUH?"); 
      } 

      } 

      // Make sure output is flushed to client. It will be, but 
      // just in case... 
      output.flush(); 
     } 

     // We're done with this client. Close his socket. 
     clientSocket.shutdownOutput(); 
     clientSocket.close(); 
     System.out.println("Closed client socket"); 
     } 

     catch (IOException e) { 
     System.out.println("accept failed"); 
     e.printStackTrace(); 
     System.exit(1); 
     } 

     System.out.println("Hello world"); 
    } 

    } 
} 
+0

謝謝!!!!!! – Bobby

2

問題是沒有人真的發送任何行。這是你的客戶做什麼:

output.print(text); //sends null 
while ((text = input.readLine()) != null){ //waits to receive a line 

這最後一部分是你的客戶端停止,因爲它等待輸入,服務器永遠不會發送。因此,這裏的服務器停止其中:

msg = input.readLine(); //waits to recieve a line 

它從來沒有在null讀取,因爲你沒有發線(例如用'\n'結束)。您可以通過用output.println()呼叫替換您的output.print()來輕鬆解決此問題,以便您的讀者知道該線路已結束並可以立即閱讀。

+0

感謝您的解釋 – Bobby