2014-01-08 59 views
-2

如何將IP地址作爲參數? 在這種形式下,程序不會在屏幕上顯示文本,而是編譯並運行。將套接字打開到某個主機的程序

import java.net.*; 
import java.io.*; 
public class Client 
{ 
    public static void main(String[]args) 
    { 
    try 
    { 

     Socket _clientSocket = new Socket(" 141.85.94.75 ",80); 
     OutputStream _outputStream = _clientSocket.getOutputStream(); 
     InputStream _inputStream = _clientSocket.getInputStream(); 

     _outputStream.write("GET /index.htmlHTTP/1.1".getBytes()); 

     int _char; 
     while((_char = _inputStream.read()) != -1) 
     { 
     System.out.print((char)_char); 
     } 

     _clientSocket.close(); 
    } 
    catch(IOException _ioe){ 
     System.out.println("Communication problem: " + _ioe.getMessage()); 
    } 
    } 

} 
+1

您知道,您不需要在下劃線前綴Java變量,對吧?你準確的問題是什麼?另外,您的GET請求不正確。 –

+0

你希望將IP地址作爲參數還是要提示用戶?你期待什麼樣的輸出? – thegrinner

+2

這裏有更多的問題......你的GET字符串不正確(缺少空格和強制回車/新行);你的ip地址在字符串中也有空格(應該是「141.85.94.75」)。 –

回答

0

您在錯誤的地方有空位。他們確實很重要。

Socket _clientSocket = new Socket("141.85.94.75",80); // note no spaces. 
    OutputStream _outputStream = _clientSocket.getOutputStream(); 
    InputStream _inputStream = _clientSocket.getInputStream(); 

    // you have to have a space and a newline. 
    _outputStream.write("GET /index.html HTTP/1.1\r\n".getBytes()); 

當我試着這個地址的網站似乎是關閉了。我會確保它首先在瀏覽器中運行。

1

你可以試試這個程序,它會提示用戶輸入IP地址:如果你想通過IP地址和端口號作爲Java程序參數

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

public class Client { 
    public static void main(String[] args) { 
     try { 
      Socket clientSocket = new Socket(getIpAddress(), 80); 
      OutputStream outputStream = clientSocket.getOutputStream(); 
      InputStream inputStream = clientSocket.getInputStream(); 

      outputStream.write("GET/index.htmlHTTP/1.1".getBytes()); 

      int character; 
      while ((character = inputStream.read()) != -1) { 
       System.out.print((char) character); 
      } 

      clientSocket.close(); 
     } catch (IOException ioe) { 
      System.out.println("Communication problem: " + ioe.getMessage()); 
     } 
    } 

    private static String getIpAddress() throws IOException{ 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     System.out.print("Enter IP Address: "); 
     return br.readLine();  
    } 

} 

或者,那麼你可以嘗試此代碼片段:

try{ 

    String hostName = args[0]; 
    int portNumber = Integer.parseInt(args[1]); 

    Socket clientSocket = new Socket(hostName, portNumber); 
    ...... 
} 
+0

+1用於消除作者代碼中令人不安的下劃線。 –

相關問題