嘿,伙计们,我需要连接到IP地址"127.0.0.1:4000",问题是我在C#中找不到这样做的方法,WebRequest只支持URI(据我所知),我也找不到一个套接字函数来做这件事。如果能帮上忙就太好了,谢谢,麦克斯
发布于 2010-02-06 15:38:20
您可以设置HttpWebRequest的Proxy属性,这应该可以做到这一点。
非常好的简单示例here (虽然是用VB编写的,但翻译起来并不难)..
发布于 2010-02-07 02:21:45
谢谢大家的帮助,我找到了我想要的东西!
<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;
}再次感谢你的帮助,不可能有其他方式找到它。
发布于 2010-02-06 15:36:49
您可以使用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();
}
}备注:如果是二进制协议,应该直接对套接字进行读写,而不使用StreamWriter和StreamReader。
https://stackoverflow.com/questions/2212422
复制相似问题