C#之网络

时间:2021-04-25 22:23:57

首先很不好意思,前段时间把评论的功能给关掉啦,BUT NOW 此功能以开放,欢迎小伙伴们拍砖。


1网络

  在网络环境下,我们最感兴趣的两个名称空间是System.Net和System.Net.Sockets.  System.Net名称空间通常与交高价的操作有关,例如 上传和下载 使用Http和其他协议进行Web请求等,而System.Net.Sockets名 称空间包含的类通常与较低层的操作有关.如果要直接使用套接字或 TCP/P之 类 的协议,这 个名 称空间 中 的类就非 常有用 .

2WebClient类

  如 果只想从特定的URl请求文件,则可以使用的最简单的.Net类是System.Net.WebClient

2.1下载文件

DEMO:

  WebClient client = new WebClient();
             Stream stream = client.OpenRead("http://www.baidu.com");
             StreamReader reader = new StreamReader(stream);
             string line = null;
             while ((line = reader.ReadLine()) != null)
             {
                 Console.WriteLine(line);
             }
             reader.Close();
             stream.Close();
             Console.ReadLine();

2.2文件上传

  WebClient类还提供了UploadFile()和UploadData()方法。尽管这个类使用起来比较方便,但是它的功能非常有限,特别是不能使用它提供身份验证。

3WebRequest类和WebResponse类

  WebRequet类代表要给某个特定的URL发送信息的请求,URL作为参数传递给Create()方法。WebResponse类代表从服务器检索数据,调用WebRequest.GetResponse()方法,实际上是把请求发给Web服务器,并创建一个Response对象,以检查返回数据。

  WebRequest wrq = WebRequest.Create("http://www.ithome.com/");
             WebResponse wrs = wrq.GetResponse();
             Stream stream = wrs.GetResponseStream();
             StreamReader reader = new StreamReader(stream);
             string line;
             while ((line = reader.ReadLine()) != null)
             {
                 Console.WriteLine(line);
             }
             stream.Close();
             Console.ReadLine();

3.1身份验证

WebRequest类中的另一个属性是Credentials属性。如果需要身份验证证书附带在请求中,就可以用用户名和密码创建NetworkCredential类的一个实例,在调用GetResponse()方法之前。

   NetworkCredential nc = new NetworkCredential("username","password");
             wrq.Credentials = nc;

3.2使用代理

许多公司都需要使用代理服务器进行所有类型的Http或FTP请 求。 代理服务器常常使用 某种形式的安全性(通 常是用户名和密码),路 由公司 的所有请求和响应 。 对于使用 WebClient对象或WebRequest对象的应用程序,需 要考虑这些代理服务器,同上,在调用之前需要使用WebProxy对象

 WebProxy wp = new WebProxy("192.168.1.100",true);
             wp.Credentials= new NetworkCredential("username", "password");
             WebRequest wrq = WebRequest.Create("http://www.ithome.com/");
             wrq.Proxy = wp;
             WebResponse wrs = wrq.GetResponse();
如果除了证书之外,还需要设计用户的域,就应在NetworkCredential实例上使用另外一个签名
  WebProxy wp = new WebProxy("192.168.1.100",true);
             wp.Credentials= new NetworkCredential("username", "password","domain");
             WebRequest wrq = WebRequest.Create("http://www.ithome.com/");
             wrq.Proxy = wp;
             WebResponse wrs = wrq.GetResponse();

4把输出的结果显示为HTML页面

  Process myproess = new Process();
             myproess.StartInfo.FileName = "iexplore.exe";
             myproess.StartInfo.Arguments = "http://www.ithome.com/";
             myproess.Start();

上面的代码会把IE作为单独的窗口打开,而应用程序并没有与新窗口相连,因此不能控制浏览器。

4.1从应用程序进行简单的web浏览

如果想在应用程序打开网页就可以使用WebBrowser控件。

5实用工具类

5.1URL

Url和 UrlBulider是System (注意:不是 system.Net)名称空间 中的两个类 ,它们都用 于表示 URI。UriBuilder类允许把给定的字符串当作URL的组成部分,从而构建一个URL。

 Uri url = new Uri("http://www.ithome.com");

5.2 IP地址和DNS名称

   用于IP地址的.NET类IPAdress类和IPHostEntry

6较底层的协议

  • Socket 这个底层的类用于管理连接,WebRequest ,TcpClient等类在内部使用这个类
  • NetworkStream 这个类从Stream派生的,它表示来自网络的数据流。
  • SmtpClient 允许通过SMTP发送消息(邮件)
  • TcpClient 允许创建和使用TCP连接
  • TcpListener 允许侦听引入的TCP连接请求
  • UdpClient 用于为UDP客户创建(UDP是TCP的一种替代协议,但它主要用于本地网络)

6.1使用SmtpClient

SmtpClient 对象可以通过SMTP传送邮件消息,

  MailMessage myMail = new MailMessage();                //发送端到接收端的邮箱地址
            myMail = new MailMessage("发送人@163.com", "收件人@qq.com");
            myMail.Subject = ";
            //建立发送对象client,验证邮件服务器,服务器端口,用户名,以及密码
            SmtpClient client = );
            client.Credentials = new NetworkCredential("用户名", "密码");
            client.Send(myMail);

但是有一个问题,这个方法再发送多余10条邮件的时候会报错,下面附上可发多条的方法

 public void SendEmail()
         {

             //smtp.163.com
             string senderServerIp = "123.125.50.133";
             //smtp.gmail.com
             //string senderServerIp = "74.125.127.109";
             //smtp.qq.com
             //string senderServerIp = "58.251.149.147";
             //string senderServerIp = "smtp.sina.com";
             string toMailAddress = "";//收件邮箱
             string fromMailAddress = "";
             ";//邮件标题
             string bodyInfo = "";//邮件内容
             string mailUsername = "";//发送邮箱的用户名(不带@qq.com)
             string mailPassword = ""; //发送邮箱的密码()
             ";
             //  string attachPath = "E:\\123123.txt; E:\\haha.pdf";

             MyEmail email = new MyEmail(senderServerIp, toMailAddress, fromMailAddress, subjectInfo, bodyInfo, mailUsername, mailPassword, mailPort, false, false);
             //  email.AddAttachments(attachPath);
             email.Send();
             MessageBox.Show("OK!");

         }

     }

     public class MyEmail
     {
         private MailMessage mMailMessage;   //主要处理发送邮件的内容(如:收发人地址、标题、主体、图片等等)
         private SmtpClient mSmtpClient; //主要处理用smtp方式发送此邮件的配置信息(如:邮件服务器、发送端口号、验证方式等等)
         private int mSenderPort;   //发送邮件所用的端口号(htmp协议默认为25)
         private string mSenderServerHost;    //发件箱的邮件服务器地址(IP形式或字符串形式均可)
         private string mSenderPassword;    //发件箱的密码
         private string mSenderUsername;   //发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为:hello)
         private bool mEnableSsl;    //是否对邮件内容进行socket层加密传输
         private bool mEnablePwdAuthentication;  //是否对发件人邮箱进行密码验证

         ///<param name="server">发件箱的邮件服务器地址</param>
         ///<param name="toMail">收件人地址(可以是多个收件人,程序中是以“;"进行区分的)</param>
         ///<param name="fromMail">发件人地址</param>
         ///<param name="subject">邮件标题</param>
         ///<param name="emailBody">邮件内容(可以以html格式进行设计)</param>
         ///<param name="username">发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为:hello)</param>
         ///<param name="password">发件人邮箱密码</param>
         ///<param name="port">发送邮件所用的端口号(htmp协议默认为25)</param>
         ///<param name="sslEnable">true表示对邮件内容进行socket层加密传输,false表示不加密</param>
         ///<param name="pwdCheckEnable">true表示对发件人邮箱进行密码验证,false表示不对发件人邮箱进行密码验证</param>
         public MyEmail(string server, string toMail, string fromMail, string subject, string emailBody, string username, string password, string port, bool sslEnable, bool pwdCheckEnable)
         {
             try
             {
                 mMailMessage = new MailMessage();
                 mMailMessage.To.Add(toMail);
                 mMailMessage.From = new MailAddress(fromMail);
                 mMailMessage.Subject = subject;
                 mMailMessage.Body = emailBody;
                 mMailMessage.IsBodyHtml = true;
                 mMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                 mMailMessage.Priority = MailPriority.Normal;
                 this.mSenderServerHost = server;
                 this.mSenderUsername = username;
                 this.mSenderPassword = password;
                 this.mSenderPort = Convert.ToInt32(port);
                 this.mEnableSsl = sslEnable;
                 this.mEnablePwdAuthentication = pwdCheckEnable;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.ToString());
             }
         }

         ///<summary>
         /// 添加附件
         ///</summary>
         ///<param name="attachmentsPath">附件的路径集合,以分号分隔</param>
         public void AddAttachments(string attachmentsPath)
         {
             try
             {
                 string[] path = attachmentsPath.Split(';'); //以什么符号分隔可以自定义
                 Attachment data;
                 ContentDisposition disposition;
                 ; i < path.Length; i++)
                 {
                     data = new Attachment(path[i], MediaTypeNames.Application.Octet);
                     disposition = data.ContentDisposition;
                     disposition.CreationDate = File.GetCreationTime(path[i]);
                     disposition.ModificationDate = File.GetLastWriteTime(path[i]);
                     disposition.ReadDate = File.GetLastAccessTime(path[i]);
                     mMailMessage.Attachments.Add(data);
                 }
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.ToString());
             }
         }

         ///<summary>
         /// 邮件的发送
         ///</summary>
         public void Send()
         {
             try
             {
                 if (mMailMessage != null)
                 {
                     mSmtpClient = new SmtpClient();
                     mSmtpClient.Host = this.mSenderServerHost;
                     mSmtpClient.Port = this.mSenderPort;
                     mSmtpClient.UseDefaultCredentials = false;
                     mSmtpClient.EnableSsl = this.mEnableSsl;
                     if (this.mEnablePwdAuthentication)
                     {
                         System.Net.NetworkCredential nc = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                         mSmtpClient.Credentials = nc.GetCredential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");
                     }
                     else
                     {
                         mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                     }
                     mSmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                     mSmtpClient.Send(mMailMessage);
                 }
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.ToString());
             }
         }
     }

SendEmail

6.2使用TCP类  

传输控制协议(TCP)类为连接和发送两个端点之间的数据提供了简单的方法。端点是IP地址和端口号的组合。TcpClient类封装了TCP连接,提供了许多属性来控制连接,包括缓冲,缓冲区的大小和超时,通过GetStream()方法请求NetworkStream对象是可以附带读写功能。  TcpListener类用start()方法侦听引入的TCP连接,当连接请求到达时,可使用AcceptSocket()方法返回一个套接字,以与远程的计算机通信,或使用AcceptTcpClient()方法通过高层的TcpClient对象进行通讯。

6.3TCP和UDP

UDP是一个几乎没有什么功能的简单协议 ,且几乎没有什么系统开销。 开发人员常常在速度和性能要求比可靠性更高的应用程序中使用 UDP,例如,视频流。 相反,TCP提 供了许多功能来确保数据的传输,它还提供 了错误校正,和 当数据丢失或数据包损坏时重新传输它们 的功能。 最后,TCP可 缓存传入和传出的数据,还保证在传输过程中,在把数据包传送给应用程序之前,重 组杂乱的一系列数据包。 即使有一些额外的开销,TCP仍是在 internet 上使用最广泛的协议,因 为它有非常高的可靠性 。

6.4UDP类

   UdpClient udpclient = new UdpClient();
             string sendMsg = "Hello";
             byte[] sendBytes = Encoding.ASCII.GetBytes(sendMsg);
             udpclient.Send(sendBytes,sendBytes.Length,);
             IPEndPoint endPoint = ,);
             byte[] rcvBytes = udpclient.Receive(ref endPoint);
             ,rcvBytes.Length);

6.5TcpSend和TcpReceive示例

TcpSend端代码:
  TcpClient tcpClient = new TcpClient(主机,端口号);
              NetworkStream ns = tcpClient.GetStream();
              FileStream fs = File.Open("Form1.cs",FileMode.Open);

            int data = fs.ReadByte();

             )
            {
                ns.WriteByte((byte)data);
                  data = fs.ReadByte();
             }
              fs.Close();
             ns.Close();
              tcpClient.Close();
TcpReceive端:
 
  Thread theard = new Thread(new ThreadStart(Listen)); //winfrom程序,只有一个textBox为txtDisplay
             theard.Start();//为避免界面假死,放到线程中

   public void Listen()
          {
              IPAddress localAddr = IPAddress.Parse("127.0.0.1");//本机
             ;//端口号要与tcpSend端一致
             TcpListener tcpListenter = new TcpListener(localAddr, port);
              tcpListenter.Start();

              TcpClient tcpClient = tcpListenter.AcceptTcpClient();
              NetworkStream ns = tcpClient.GetStream();
              StreamReader sr = new StreamReader(ns);
              string result = sr.ReadToEnd();
              Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });
              tcpClient.Close();
            tcpListenter.Stop();
          }

          public void UpdateDisplay(string text)
         {
             txtDisplay.Text = text;
         }
      }
      public delegate void UpdateDisplayDelegate(string text);

6.5 Socket类

  Socket类提供了网络编程中*的控制。  构建服务器控制台应用程序:
 Console.WriteLine("Stating:Creating Socket object");
             Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             listener.Bind());
             listener.Listen();

             while (true)
             {
                 Console.WriteLine("Wait for content");
                 Socket socket = listener.Accept();
                 string receiveMsg = string.Empty;
                 while (true)
                 {
                     ];
                     int numBytes = socket.Receive(bytes);
                     Console.WriteLine("Receiveving...");
                     receiveMsg += Encoding.ASCII.GetString(bytes, , numBytes);
                     )
                     {
                         break;
                     }
                 }
                 Console.WriteLine("Receivevalue:{0}",receiveMsg);
                 string replyValue = "Message successfully received";
                 byte[] replyByte = Encoding.ASCII.GetBytes(replyValue);
                 socket.Send(replyByte);
                 socket.Shutdown(SocketShutdown.Both);
                 socket.Close();
             }
             listener.Close();
         }
客户端代码:
   ];
             IPHostEntry ipHost = Dns.Resolve("127.0.0.1");
             IPAddress ipAddress = ipHost.AddressList[];
             IPEndPoint ipEndPoint = );
             Console.WriteLine("Starting : Creating Socket object");
             Socket sender = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
             sender.Connect(ipEndPoint);

             Console.WriteLine("Successfully contendted to {0}",sender.RemoteEndPoint);

             string sendingMessage = "Hello";
             Console.WriteLine("Creating message:Hello World");
             byte[] forwardMessage = Encoding.ASCII.GetBytes(sendingMessage+"[FINAL]");
             sender.Send(forwardMessage);
             int totalBytesReceived = sender.Receive(receivedBytes);
             Console.WriteLine(,totalBytesReceived));
             sender.Shutdown(SocketShutdown.Both);
             sender.Close();
             Console.ReadKey();
6.6WebsocketWebsocket协议用于完全双工的通信,一般在浏览器和服务器之间通信。
 <!doctype html>
 <head>
     <meta http-equiv="X-UA-Compatible" content="IE=edge" />
     <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
     <title>WroxChat</title>
     <script type="text/javascript">
         $(document).ready(function () {
             var name = prompt('what is your name?:');
             var url = 'ws://localhost/ws.ashx?name=' + name;
             ws = new WebSocket(url);
             ws.onopen = function () {
                 $('#messages').prepend('Connected <br/>');
                 $('#cmdSend').click(function () {
                     ws.send($('#txtMessage').val());
                     $('#txtMessage').val('');
                 });
             };
             ws.onmessage = function (e) {
                 $('#chatMessages').prepend(e.data + '<br/>');
             };
             $('#cmdLeave').click(function () {
                 ws.close();
             });
             ws.onclose = function () {
                 $('#chatMessages').prepend('Closed <br/>');
             };
             ws.onerror = function (e) {
                 $('#chatMessages').prepend('Oops something went wront <br/>');
             };
         });
     </script>
 </head>
 <body>
 <input id="txtMessage" />
 <input id="cmdSend" type="button" value="Send" />
 <input id="cmdLeave" type="button" value="Leave" />
 <br />
 <div id="chatMessages" />
 </body>

客户端


  public class ws : IHttpHandler
     {

         public void ProcessRequest(HttpContext context)
         {
             if (context.IsWebSocketRequest)
             {
                 var chatuser = new ChatUser();
                 chatuser.UserName = context.Request.QueryString["name"];
                 ChatApp.AddUser(chatuser);
                 context.AcceptWebSocketRequest(chatuser.HandleWebSocket);

             }

         }

         public bool IsReusable
         {
             get
             {
                 return false;
             }
         }
     }
 public class ChatApp
     {
         static IList<ChatUser> _users = new List<ChatUser>();

         public static void AddUser(ChatUser chatUser)
         {
             _users.Add(chatUser);
             foreach(var user in _users)
             {
                 user.SendMessage(chatUser.UserName + " joined the chat!");
             }
         }

         public static void BroadcastMessage(string message)
         {
             foreach (var user in _users)
             {
                 user.SendMessage(message);
             }
         }
     }
 public class ChatUser
     {
         WebSocketContext _context;
         public string UserName { get; set; }

         public async Task HandleWebSocket(WebSocketContext wsContext)
         {
             _context = wsContext;
             ;
             byte[] receiveBuffer = new byte[maxMessageSize];
             WebSocket socket = _context.WebSocket;

             while (socket.State == WebSocketState.Open)
             {
                 WebSocketReceiveResult receiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);

                 if (receiveResult.MessageType == WebSocketMessageType.Close)
                 {
                     await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                 }
                 else if (receiveResult.MessageType == WebSocketMessageType.Binary)
                 {
                     await socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept binary frame", CancellationToken.None);
                 }
                 else
                 {
                     , receiveResult.Count);
                     var echoString = string.Concat(UserName, " said: ", receivedString);
                     ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(echoString));

                     ChatApp.BroadcastMessage(echoString);
                 }
             }
         }
         public async Task SendMessage(string message)
         {
             if (_context != null && _context.WebSocket.State == WebSocketState.Open)
             {
                 var outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message));
                 await _context.WebSocket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
             }
         }

     }

服务端