Компьютерный форум NoWa.cc Здесь может быть Ваша реклама
Правила Форума
редакция от 22.06.2020
Портал .::2BakSa.WS::.
Вернуться   Компьютерный форум NoWa.cc > В помощь вебмастеру > Программирование > .NET

Уважаемые пользователи nowa.cc и 2baksa.ws. У нас сложилось тяжёлое финансовое положение. Мы работаем для вас вот уже более 15 лет и сейчас вынуждены просить о помощи. Окажите посильную поддержку проектам. Мы очень надеемся на вас. Реквизиты для переводов ниже.
Webmoney Webmoney WMZ: 826074280762 Webmoney WME: 804621616710
PayPal PayPal_Email E-mail для связи по вопросу помощи
Кошелёк для вашей помощи YooMoney 4100117770549562
YooMoney Спасибо за поддержку!
Ответ
 
Опции темы Опции просмотра 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);
    }
}
nbit вне форума
 
Ответить с цитированием Вверх
Здесь может быть Ваша реклама
Здесь может быть Ваша реклама


Реклама: В КНС всегда быстро, выгодно, удобно: MZ-V8P1T0CW - билеты на футбол в подарок каждому покупателюВсегда выгодно в KNSneva.ru - монитор AOC - доставкой по Санкт-Петербургу и СЗАОшезлонги пластиковые купитьполировальный ювелирный станок купитьConecte FreshSales CRM a Suitedash


Старый 11.03.2015, 14:27   #2
Fistashk0
Новичок
 
Пол:Мужской
Регистрация: 11.03.2015
Сообщений: 5
Репутация: 5
По умолчанию Re: Из синхронного сокета в асинхронный

Цитата:
Сообщение от nbit Посмотреть сообщение
В 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);
    }
}

Для асинхронных операций в C# можно использовать класс BackgroundWorker. Можно использовать его , а можно просто создать отдельный поток и описать загрузку в нем.
Fistashk0 вне форума
 
Ответить с цитированием Вверх
Ответ


Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.

Быстрый переход


Текущее время: 15:39. Часовой пояс GMT +3.


Copyright ©2004 - 2024 2BakSa.WS

Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2024, vBulletin Solutions, Inc. Перевод: zCarot
Время генерации страницы 0.12857 секунды с 10 запросами