通过Socket套接字和NetWorkStream流进行网络传输

 通过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());}
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值