通过Socket套接字和NetWorkStream流进行网络传输,通过NetWork流来发出链接的要求字符串得到Google主页网站的源代码,利用Socket套接字来链接Google的服务器发送请求和接收数据完成网络传输功能,主要利用了Dns类获取IPAddress来建立链接,以后还有讲到利用TCP和UDP进行通信在封装了Socket类的基础上能够更容易的实现网络的通信。

源代码如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Net;
using System.Net.Sockets;
namespace NetPortConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            string server;
            IPAddress[] hostadd;
            ShowIPAddressAll(out server, out hostadd);
            Socket s = Connect(hostadd);
            NetworkStream ns = new NetworkStream(s, FileAccess.ReadWrite);
            byte[] request = Request(server, s, ns);
            //利用套接字发送
            s.Send(request, request.Length, SocketFlags.None);
            Receive(s);
            Console.ReadLine();
        }
        private static void Receive(Socket s)
        {
            int bytes;
            byte[] RecBytes = new byte[256];
            while ((bytes = s.Receive(RecBytes, RecBytes.Length, SocketFlags.None)) > 0){
                Console.WriteLine(Encoding.Unicode.GetString(RecBytes, 0, bytes));
            }
        }

        private static byte[] Request(string server, Socket s, NetworkStream ns){
            //需要这样的格式
            string opStr = "GET/HTTP/1.1  /r/n Host:" + server + "/r/nConnection:Close/r/n/r/n";
            byte[] request = Encoding.Unicode.GetBytes(opStr);

            ns.Write(request, 0, request.Length);
            int nextByte;
            while ((nextByte = ns.ReadByte()) != -1){
                Console.Write((char)nextByte);
            }
            return request;
        }

        private static Socket Connect(IPAddress[] hostadd){
            IPEndPoint iep = new IPEndPoint(hostadd[0], 80);
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(iep);
            if (!s.Connected){Console.WriteLine("Unable to Connect to host");}
            return s;
        }
        private static void ShowIPAddressAll(out string server, out IPAddress[] hostadd){
            server = "www.google.com";
            hostadd = (Dns.GetHostEntry(server)).AddressList;
            Console.WriteLine("Ip Address for {0} are:", server);
            for (int i = 0; i < hostadd.Length; i++){Console.WriteLine(hostadd[i].ToString());}
        }
    }
}

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐