Правила Форума редакция от 22.06.2020 |
|
|
|
|
|
Опции темы | Опции просмотра | Language |
28.10.2011, 08:17 | #1 |
Неактивный пользователь
Пол: Регистрация: 28.10.2011
Сообщений: 1
Репутация: 0
|
Из синхронного сокета в асинхронный
В MSDN есть замечательный пример получения кода html страницы пример (ссылка), но к сожалению в этом примере производится блокирование до тех пор, пока не будет принята вся страница. Если не сложно помогите пожалуйста переделать его под асинхронные сокеты, буду премного благодарен за помощь.
Код:
using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; 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. private static string SocketSendReceive(string server, int port) { string request = "GET / HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; Byte[] bytesSent = Encoding.ASCII.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.ASCII.GetString(bytesReceived, 0, bytes); } while (bytes > 0); return page; } public static void Main(string[] args) { string host; int port = 80; if (args.Length == 0) // If no server name is passed as argument to this program, // use the current host name as the default. host = Dns.GetHostName(); else host = args[0]; string result = SocketSendReceive(host, port); Console.WriteLine(result); } } |
Реклама: | В КНС всегда быстро, выгодно, удобно: MZ-V8P1T0CW - билеты на футбол в подарок каждому покупателю | Всегда выгодно в KNSneva.ru - монитор AOC - доставкой по Санкт-Петербургу и СЗАО | шезлонги пластиковые купить | полировальный ювелирный станок купить | Conecte FreshSales CRM a Suitedash |
11.03.2015, 14:27 | #2 | |||||||||||||||||||||||
Новичок
Пол: Регистрация: 11.03.2015
Сообщений: 5
Репутация: 5
|
Re: Из синхронного сокета в асинхронный
Для асинхронных операций в C# можно использовать класс BackgroundWorker. Можно использовать его , а можно просто создать отдельный поток и описать загрузку в нем. |
|||||||||||||||||||||||
Сказали спасибо: |