首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >请求本地WebPage

请求本地WebPage
EN

Stack Overflow用户
提问于 2010-02-06 15:33:46
回答 3查看 86关注 0票数 1

嘿,伙计们,我需要连接到IP地址"127.0.0.1:4000",问题是我在C#中找不到这样做的方法,WebRequest只支持URI(据我所知),我也找不到一个套接字函数来做这件事。如果能帮上忙就太好了,谢谢,麦克斯

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-02-06 15:38:20

您可以设置HttpWebRequest的Proxy属性,这应该可以做到这一点。

非常好的简单示例here (虽然是用VB编写的,但翻译起来并不难)..

票数 1
EN

Stack Overflow用户

发布于 2010-02-07 02:21:45

谢谢大家的帮助,我找到了我想要的东西!

代码语言:javascript
复制
<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;
    }

再次感谢你的帮助,不可能有其他方式找到它。

票数 1
EN

Stack Overflow用户

发布于 2010-02-06 15:36:49

您可以使用TcpClient或原始Socket

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2212422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档