Нужна помощь с сокетами на C#

Discussion in 'С/С++, C#, Rust, Swift, Go, Java, Perl, Ruby' started by l.sEw.l, 27 Oct 2008.

  1. Algol

    Algol New Member

    Joined:
    29 May 2002
    Messages:
    1,759
    Likes Received:
    4
    Reputations:
    0
    Да уж, меганеудобно :D :D

    Code:
    using System;
    using System.Net;
    using System.IO;
    using System.Net.Sockets;
    using System.Text;
    
    class SimplestWebBrowser
    {
    	[STAThread]
    	static void Main(string[] args)
    	{
    		Console.Write("Enter URL (for example http://google.com ):");
    		string URL = Console.ReadLine();
            //парсим
            string[] parts = URL.Split(new char[]{'/'}, 4);
            if(parts.Length<3)
                throw new Exception ("Bad URL");
            string host = parts[2];
            //открываем сокет
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(host, 80);
            //отправляем запрос
            byte[] buffer = Encoding.Default.GetBytes(
                string.Format(
    @"GET /{0} HTTP/1.0
    Host: {1}
    
    ", parts.Length>3?parts[3]:"", host));
            socket.Send(buffer);
            //принимаем ответ
            byte[] recBuffer = new byte[4096];//принмаем максимум 4 кб за раз
            string answer = "";
            int recCount;
            do
            {
                recCount = socket.Receive(recBuffer);
                //перобразуем в ASCII
                answer += Encoding.Default.GetString(recBuffer, 0, recCount); 
            } while (recCount > 0);
            //скажем серверу пока
            socket.Close();
            //покажем ответ
            Console.WriteLine(answer);
            Console.ReadLine();
    	}
    }