嘿伙计们,我需要连接到IP地址“127.0.0.1:4000”,问题是我找不到在C#中做到这一点的方法,WebRequest只支持URI(据我所知),以及我也找不到套接字函数。 任何帮助都会很棒, 谢谢, 最大
答案 0 :(得分:1)
答案 1 :(得分: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;
}
再次感谢您的帮助,无法以任何其他方式找到它。
答案 2 :(得分:0)
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
。