Для формирования запросов и получения ответов сервера использовать функции для работы с сокетами/ Есть взятый из msdn кусок
| Код | public class GetSocket { private static Socket ConnectSocket(string server, int port) { Socket s = null; IPHostEntry hostEntry = null;
// Get host related information. hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid // an exception that occurs when the host IP Address is not compatible with the address family // (typical in the IPv6 case). foreach (IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, port); Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected) { s = tempSocket; break; } else { continue; } } return s; }
// This method requests the home page content for the specified server. public static string SocketSendReceive(string server, int port, string pages) { //string pages = "/info/studcity/"; string request = ""; pages = "/" + pages + "/"; if (pages != "") request = "GET " + pages + " HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; else request = "GET / HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; Byte[] bytesSent = Encoding.Default.GetBytes(request); Byte[] bytesReceived = new Byte[256];
// Create a socket connection with the specified server and port. Socket s = ConnectSocket(server, port);
if (s == null) return ("Connection failed");
// Send request to the server. s.Send(bytesSent, bytesSent.Length, 0);
// Receive the server home page content. int bytes = 0; string page = "Default HTML page on " + server + ":\r\n";
// The following will block until te page is transmitted. do { bytes = s.Receive(bytesReceived, bytesReceived.Length, 0); page = page + Encoding.Default.GetString(bytesReceived, 0, bytes); } while (bytes > 0);
return page; } } |
и свои попытки поиска ссылок по коду страницы
| Код | string result = ""; int port = Convert.ToInt32(textBox2.Text); string myhost = Convert.ToString(textBox1.Text); listHREF = new List<string>(); listHREF.Add(myhost); k++;
result = GetSocket.SocketSendReceive(myhost, port, ""); //выводится полученный код страницы richTextBox1.Text = result;
//выделяем все ссылки int startindex = 0; int endindex = 0; int value = 0; string s; long n = result.Length; while (value != -1) { value = result.IndexOf("<a href=");
if (value != -1) { startindex = value + 9; endindex = result.IndexOf("\"", startindex) - 1; s = result.Substring(startindex, endindex - startindex + 1); if (!listHREF.Contains<string>(s)) { listHREF.Add(s); k++; } result = result.Substring(endindex + 1); } } |
Про Content-Length в заголовке знаю, но как то не всегда встречается.. как считать размер страницы, если нет Content-Length? спасибо за помощь... |