zoukankan      html  css  js  c++  java
  • 控制台浏览器代码实战

    本文章代码只是为了能够深刻的了解网络通讯,主要功能是获取网页内容,无须把代码背出来,只须看懂,能改改就行了

    首先需要创建Socket

    //注意在VS2010中需要写成:new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))//因为Socket继承于IDisposable,所以要using起来
                //连接服务器。http协议默认的端口号是80。每个服务器软件监听一个端口(别的软件就不能监听这个端口了),
                //发送给这个端口的数据只会被这个服务器软件接收到。
                {
                    socket.Connect(new DnsEndPoint("127.0.0.1", 8080));//这里的127.0.0.1可以写成域名地址,因为Socket不知道是什么端口号,所以要写上端口号,网站的端口号一般为80
                    //读写socket通讯数据的流
                    using (NetworkStream netStream = new NetworkStream(socket))
                    using (StreamWriter writer = new StreamWriter(netStream))
                    {
                        writer.WriteLine("GET /123.html HTTP/1.1");//123.html表示要获取的页面,每一行指令都回车一下
                        writer.WriteLine("HOST:127.0.0.1:8080");
                        writer.WriteLine();//空行回车,表示指令结束
                    }
                    using (NetworkStream netStream = new NetworkStream(socket))
                    using (StreamReader reader = new StreamReader(netStream))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)//第一种写法
                        //while (!reader.EndOfStream)//第二种写法
                        {
                            //Console.WriteLine(line);
                            Console.WriteLine(reader.ReadLine());
                        }
                    }
                }

    执行结果:

  • 相关阅读:
    [React Intl] Format Numbers with Separators and Currency Symbols using react-intl FormattedNumber
    [React Intl] Format a Date Relative to the Current Date Using react-intl FormattedRelative
    [React Intl] Format Date and Time Using react-intl FormattedDate and FormattedTime
    [React Intl] Render Content with Markup Using react-intl FormattedHTMLMessage
    带你走进EJB--MDB
    Google Play和基于Feature的过滤 —— Feature 参考手册
    常见排序算法的实现
    Never-build package 'XXXX' requires always-build package 'EhLib70'
    自制的七个C,总结的太好了
    那些有影响力的语言
  • 原文地址:https://www.cnblogs.com/genesis/p/4652778.html
Copyright © 2011-2022 走看看