2010-02-06 66 views
1

嘿,我需要連接到IP地址「127.0.0.1:4000」,問題是我找不到在C#中這樣做的方式,WebRequest只支持URI(就我的知識而言),並且我找不到一個套接字函數來執行它。 任何幫助,這將是巨大的, 謝謝, 最大請求本地網頁

+2

一個ip端口組合,你寫它是一個完全有效的URI – 2010-02-06 07:40:16

回答

1

您可以設置HttpWebRequest的Proxy屬性,應該這樣做。

相當不錯的簡單例子here(在VB中,雖然,但不是很難翻譯)..

+0

我試過你給的代碼,但它返回了我一直在遇到的錯誤,就行了: HttpWebRequest webReq =((HttpWebRequest)(WebRequest。創建(URL))); (其中url = 127.0.0.1:4000) – Ben 2010-02-06 18:08:22

0

你可以使用一個TcpClient或生Socket

using (var client = new TcpClient("127.0.0.1", 4000)) 
using (var stream = client.GetStream()) 
{ 
    using (var writer = new StreamWriter(stream)) 
    { 
     // Write something to the socket 
     writer.Write("HELLO"); 
    } 

    using (var reader = new StreamReader(stream)) 
    { 
     // Read the response until a \r\n 
     string response = reader.ReadLine(); 
    } 
} 

備註:如果它是一個二進制協議,你應該直接寫入/讀取到不使用StreamWriterStreamReader

1

感謝您的幫助球員,我發現我一直在尋找!再次

<code> 
    /// <summary> 
    /// Gets the contents of a page, using IP address not host name 
    /// </summary> 
    /// <param name="host">The IP of the host</param> 
    /// <param name="port">The Port to connect to</param> 
    /// <param name="path">the path to the file request (with leading /)</param> 
    /// <returns>Page Contents in string</returns> 
    private string GetWebPage(string host, int port,string path) 
    { 
     string getString = "GET "+path+" HTTP/1.1\r\nHost: www.Me.mobi\r\nConnection: Close\r\n\r\n"; 
     Encoding ASCII = Encoding.ASCII; 
     Byte[] byteGetString = ASCII.GetBytes(getString); 
     Byte[] receiveByte = new Byte[256]; 
     Socket socket = null; 
     String strPage = null; 
     try 
     { 
      IPEndPoint ip = new IPEndPoint(IPAddress.Parse(host), port); 
      socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
      socket.Connect(ip); 
     } 
     catch (SocketException ex) 
     { 
      Console.WriteLine("Source:" + ex.Source); 
      Console.WriteLine("Message:" + ex.Message); 
      MessageBox.Show("Message:" + ex.Message); 
     } 
     socket.Send(byteGetString, byteGetString.Length, 0); 
     Int32 bytes = socket.Receive(receiveByte, receiveByte.Length, 0); 
     strPage = strPage + ASCII.GetString(receiveByte, 0, bytes); 

     while (bytes > 0) 
     { 
      bytes = socket.Receive(receiveByte, receiveByte.Length, 0); 
      strPage = strPage + ASCII.GetString(receiveByte, 0, bytes); 
     } 
     socket.Close(); 
     return strPage; 
    } 

感謝您的幫助,不可能找到任何其他方式。