标签:
首先很不好意思,前段时间把评论的功能给关掉啦,BUT NOW 此功能以开放,欢迎小伙伴们拍砖。
在网络环境下,我们最感兴趣的两个名称空间是System.Net和System.Net.Sockets. System.Net名称空间通常与交高价的操作有关,例如 上传和下载 使用Http和其他协议进行Web请求等,而System.Net.Sockets名 称空间包含的类通常与较低层的操作有关.如果要直接使用套接字或 TCP/P之 类 的协议,这 个名 称空间 中 的类就非 常有用 .
如 果只想从特定的URl请求文件,则可以使用的最简单的.Net类是System.Net.WebClient
DEMO:
1 WebClient client = new WebClient();
2 Stream stream = client.OpenRead("http://www.baidu.com");
3 StreamReader reader = new StreamReader(stream);
4 string line = null;
5 while ((line = reader.ReadLine()) != null)
6 {
7 Console.WriteLine(line);
8 }
9 reader.Close();
10 stream.Close();
11 Console.ReadLine();
WebClient类还提供了UploadFile()和UploadData()方法。尽管这个类使用起来比较方便,但是它的功能非常有限,特别是不能使用它提供身份验证。
WebRequet类代表要给某个特定的URL发送信息的请求,URL作为参数传递给Create()方法。WebResponse类代表从服务器检索数据,调用WebRequest.GetResponse()方法,实际上是把请求发给Web服务器,并创建一个Response对象,以检查返回数据。
1 WebRequest wrq = WebRequest.Create("http://www.ithome.com/");
2 WebResponse wrs = wrq.GetResponse();
3 Stream stream = wrs.GetResponseStream();
4 StreamReader reader = new StreamReader(stream);
5 string line;
6 while ((line = reader.ReadLine()) != null)
7 {
8 Console.WriteLine(line);
9 }
10 stream.Close();
11 Console.ReadLine();
WebRequest类中的另一个属性是Credentials属性。如果需要身份验证证书附带在请求中,就可以用用户名和密码创建NetworkCredential类的一个实例,在调用GetResponse()方法之前。
1 NetworkCredential nc = new NetworkCredential("username","password");
2 wrq.Credentials = nc;
许多公司都需要使用代理服务器进行所有类型的Http或FTP请 求。 代理服务器常常使用 某种形式的安全性(通 常是用户名和密码),路 由公司 的所有请求和响应 。 对于使用 WebClient对象或WebRequest对象的应用程序,需 要考虑这些代理服务器,同上,在调用之前需要使用WebProxy对象
1 WebProxy wp = new WebProxy("192.168.1.100",true);
2 wp.Credentials= new NetworkCredential("username", "password");
3 WebRequest wrq = WebRequest.Create("http://www.ithome.com/");
4 wrq.Proxy = wp;
5 WebResponse wrs = wrq.GetResponse();
如果除了证书之外,还需要设计用户的域,就应在NetworkCredential实例上使用另外一个签名
1 WebProxy wp = new WebProxy("192.168.1.100",true);
2 wp.Credentials= new NetworkCredential("username", "password","domain");
3 WebRequest wrq = WebRequest.Create("http://www.ithome.com/");
4 wrq.Proxy = wp;
5 WebResponse wrs = wrq.GetResponse();
1 Process myproess = new Process();
2 myproess.StartInfo.FileName = "iexplore.exe";
3 myproess.StartInfo.Arguments = "http://www.ithome.com/";
4 myproess.Start();
上面的代码会把IE作为单独的窗口打开,而应用程序并没有与新窗口相连,因此不能控制浏览器。
如果想在应用程序打开网页就可以使用WebBrowser控件。
Url和 UrlBulider是System (注意:不是 system.Net)名称空间 中的两个类 ,它们都用 于表示 URI。UriBuilder类允许把给定的字符串当作URL的组成部分,从而构建一个URL。
Uri url = new Uri("http://www.ithome.com");
用于IP地址的.NET类IPAdress类和IPHostEntry
SmtpClient 对象可以通过SMTP传送邮件消息,
MailMessage myMail = new MailMessage(); //发送端到接收端的邮箱地址
myMail = new MailMessage("发送人@163.com", "收件人@qq.com");
myMail.Subject = "1";
//建立发送对象client,验证邮件服务器,服务器端口,用户名,以及密码
SmtpClient client = new SmtpClient("123.125.50.133", 25);
client.Credentials = new NetworkCredential("用户名", "密码");
client.Send(myMail);
但是有一个问题,这个方法再发送多余10条邮件的时候会报错,下面附上可发多条的方法
1 public void SendEmail()
2 {
3
4 //smtp.163.com
5 string senderServerIp = "123.125.50.133";
6 //smtp.gmail.com
7 //string senderServerIp = "74.125.127.109";
8 //smtp.qq.com
9 //string senderServerIp = "58.251.149.147";
10 //string senderServerIp = "smtp.sina.com";
11 string toMailAddress = "";//收件邮箱
12 string fromMailAddress = "";
13 string subjectInfo = "123";//邮件标题
14 string bodyInfo = "";//邮件内容
15 string mailUsername = "";//发送邮箱的用户名(不带@qq.com)
16 string mailPassword = ""; //发送邮箱的密码()
17 string mailPort = "25";
18 // string attachPath = "E:\\123123.txt; E:\\haha.pdf";
19
20 MyEmail email = new MyEmail(senderServerIp, toMailAddress, fromMailAddress, subjectInfo, bodyInfo, mailUsername, mailPassword, mailPort, false, false);
21 // email.AddAttachments(attachPath);
22 email.Send();
23 MessageBox.Show("OK!");
24
25 }
26
27 }
28
29 public class MyEmail
30 {
31 private MailMessage mMailMessage; //主要处理发送邮件的内容(如:收发人地址、标题、主体、图片等等)
32 private SmtpClient mSmtpClient; //主要处理用smtp方式发送此邮件的配置信息(如:邮件服务器、发送端口号、验证方式等等)
33 private int mSenderPort; //发送邮件所用的端口号(htmp协议默认为25)
34 private string mSenderServerHost; //发件箱的邮件服务器地址(IP形式或字符串形式均可)
35 private string mSenderPassword; //发件箱的密码
36 private string mSenderUsername; //发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为:hello)
37 private bool mEnableSsl; //是否对邮件内容进行socket层加密传输
38 private bool mEnablePwdAuthentication; //是否对发件人邮箱进行密码验证
39
40 ///<param name="server">发件箱的邮件服务器地址</param>
41 ///<param name="toMail">收件人地址(可以是多个收件人,程序中是以“;"进行区分的)</param>
42 ///<param name="fromMail">发件人地址</param>
43 ///<param name="subject">邮件标题</param>
44 ///<param name="emailBody">邮件内容(可以以html格式进行设计)</param>
45 ///<param name="username">发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为:hello)</param>
46 ///<param name="password">发件人邮箱密码</param>
47 ///<param name="port">发送邮件所用的端口号(htmp协议默认为25)</param>
48 ///<param name="sslEnable">true表示对邮件内容进行socket层加密传输,false表示不加密</param>
49 ///<param name="pwdCheckEnable">true表示对发件人邮箱进行密码验证,false表示不对发件人邮箱进行密码验证</param>
50 public MyEmail(string server, string toMail, string fromMail, string subject, string emailBody, string username, string password, string port, bool sslEnable, bool pwdCheckEnable)
51 {
52 try
53 {
54 mMailMessage = new MailMessage();
55 mMailMessage.To.Add(toMail);
56 mMailMessage.From = new MailAddress(fromMail);
57 mMailMessage.Subject = subject;
58 mMailMessage.Body = emailBody;
59 mMailMessage.IsBodyHtml = true;
60 mMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
61 mMailMessage.Priority = MailPriority.Normal;
62 this.mSenderServerHost = server;
63 this.mSenderUsername = username;
64 this.mSenderPassword = password;
65 this.mSenderPort = Convert.ToInt32(port);
66 this.mEnableSsl = sslEnable;
67 this.mEnablePwdAuthentication = pwdCheckEnable;
68 }
69 catch (Exception ex)
70 {
71 Console.WriteLine(ex.ToString());
72 }
73 }
74
75 ///<summary>
76 /// 添加附件
77 ///</summary>
78 ///<param name="attachmentsPath">附件的路径集合,以分号分隔</param>
79 public void AddAttachments(string attachmentsPath)
80 {
81 try
82 {
83 string[] path = attachmentsPath.Split(‘;‘); //以什么符号分隔可以自定义
84 Attachment data;
85 ContentDisposition disposition;
86 for (int i = 0; i < path.Length; i++)
87 {
88 data = new Attachment(path[i], MediaTypeNames.Application.Octet);
89 disposition = data.ContentDisposition;
90 disposition.CreationDate = File.GetCreationTime(path[i]);
91 disposition.ModificationDate = File.GetLastWriteTime(path[i]);
92 disposition.ReadDate = File.GetLastAccessTime(path[i]);
93 mMailMessage.Attachments.Add(data);
94 }
95 }
96 catch (Exception ex)
97 {
98 Console.WriteLine(ex.ToString());
99 }
100 }
101
102 ///<summary>
103 /// 邮件的发送
104 ///</summary>
105 public void Send()
106 {
107 try
108 {
109 if (mMailMessage != null)
110 {
111 mSmtpClient = new SmtpClient();
112 mSmtpClient.Host = this.mSenderServerHost;
113 mSmtpClient.Port = this.mSenderPort;
114 mSmtpClient.UseDefaultCredentials = false;
115 mSmtpClient.EnableSsl = this.mEnableSsl;
116 if (this.mEnablePwdAuthentication)
117 {
118 System.Net.NetworkCredential nc = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
119 mSmtpClient.Credentials = nc.GetCredential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");
120 }
121 else
122 {
123 mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
124 }
125 mSmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
126 mSmtpClient.Send(mMailMessage);
127 }
128 }
129 catch (Exception ex)
130 {
131 Console.WriteLine(ex.ToString());
132 }
133 }
134 }
6.2使用TCP类
传输控制协议(TCP)类为连接和发送两个端点之间的数据提供了简单的方法。端点是IP地址和端口号的组合。TcpClient类封装了TCP连接,提供了许多属性来控制连接,包括缓冲,缓冲区的大小和超时,通过GetStream()方法请求NetworkStream对象是可以附带读写功能。
TcpListener类用start()方法侦听引入的TCP连接,当连接请求到达时,可使用AcceptSocket()方法返回一个套接字,以与远程的计算机通信,或使用AcceptTcpClient()方法通过高层的TcpClient对象进行通讯。
UDP是一个几乎没有什么功能的简单协议 ,且几乎没有什么系统开销。 开发人员常常在速度和性能要求比可靠性更高的应用程序中使用 UDP,例如,视频流。 相反,TCP提 供了许多功能来确保数据的传输,它还提供 了错误校正,和 当数据丢失或数据包损坏时重新传输它们 的功能。 最后,TCP可 缓存传入和传出的数据,还保证在传输过程中,在把数据包传送给应用程序之前,重 组杂乱的一系列数据包。 即使有一些额外的开销,TCP仍是在 internet 上使用最广泛的协议,因 为它有非常高的可靠性 。
1 UdpClient udpclient = new UdpClient(); 2 string sendMsg = "Hello"; 3 byte[] sendBytes = Encoding.ASCII.GetBytes(sendMsg); 4 udpclient.Send(sendBytes,sendBytes.Length,"SomEchoServer.net",7); 5 IPEndPoint endPoint = new IPEndPoint(0,0); 6 byte[] rcvBytes = udpclient.Receive(ref endPoint); 7 string rcvmessage = Encoding.ASCII.GetString(rcvBytes,0,rcvBytes.Length);
TcpSend端代码:
1 TcpClient tcpClient = new TcpClient(主机,端口号); 2 NetworkStream ns = tcpClient.GetStream(); 3 FileStream fs = File.Open("Form1.cs",FileMode.Open); 4 5 int data = fs.ReadByte(); 6 7 while (data != -1) 8 { 9 ns.WriteByte((byte)data); 10 data = fs.ReadByte(); 11 } 12 fs.Close(); 13 ns.Close(); 14 tcpClient.Close();
TcpReceive端:
1 Thread theard = new Thread(new ThreadStart(Listen)); //winfrom程序,只有一个textBox为txtDisplay 2 theard.Start();//为避免界面假死,放到线程中 3 4 5 public void Listen() 6 { 7 IPAddress localAddr = IPAddress.Parse("127.0.0.1");//本机 8 int port = 2112;//端口号要与tcpSend端一致 9 TcpListener tcpListenter = new TcpListener(localAddr, port); 10 tcpListenter.Start(); 11 12 TcpClient tcpClient = tcpListenter.AcceptTcpClient(); 13 NetworkStream ns = tcpClient.GetStream(); 14 StreamReader sr = new StreamReader(ns); 15 string result = sr.ReadToEnd(); 16 Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result }); 17 tcpClient.Close(); 18 tcpListenter.Stop(); 19 } 20 21 public void UpdateDisplay(string text) 22 { 23 txtDisplay.Text = text; 24 } 25 } 26 public delegate void UpdateDisplayDelegate(string text);
6.5 Socket类
Socket类提供了网络编程中最高级的控制。
构建服务器控制台应用程序:
1 Console.WriteLine("Stating:Creating Socket object"); 2 Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 3 listener.Bind(new IPEndPoint(IPAddress.Any,2112)); 4 listener.Listen(10); 5 6 while (true) 7 { 8 Console.WriteLine("Wait for content"); 9 Socket socket = listener.Accept(); 10 string receiveMsg = string.Empty; 11 while (true) 12 { 13 byte[] bytes= new byte[1024]; 14 int numBytes = socket.Receive(bytes); 15 Console.WriteLine("Receiveving..."); 16 receiveMsg += Encoding.ASCII.GetString(bytes, 0, numBytes); 17 if (receiveMsg.IndexOf("[FINAL]") > -1) 18 { 19 break; 20 } 21 } 22 Console.WriteLine("Receivevalue:{0}",receiveMsg); 23 string replyValue = "Message successfully received"; 24 byte[] replyByte = Encoding.ASCII.GetBytes(replyValue); 25 socket.Send(replyByte); 26 socket.Shutdown(SocketShutdown.Both); 27 socket.Close(); 28 } 29 listener.Close(); 30 }
客户端代码:
1 byte[] receivedBytes = new byte[1024]; 2 IPHostEntry ipHost = Dns.Resolve("127.0.0.1"); 3 IPAddress ipAddress = ipHost.AddressList[0]; 4 IPEndPoint ipEndPoint = new IPEndPoint(ipAddress,2112); 5 Console.WriteLine("Starting : Creating Socket object"); 6 Socket sender = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); 7 sender.Connect(ipEndPoint); 8 9 Console.WriteLine("Successfully contendted to {0}",sender.RemoteEndPoint); 10 11 string sendingMessage = "Hello"; 12 Console.WriteLine("Creating message:Hello World"); 13 byte[] forwardMessage = Encoding.ASCII.GetBytes(sendingMessage+"[FINAL]"); 14 sender.Send(forwardMessage); 15 int totalBytesReceived = sender.Receive(receivedBytes); 16 Console.WriteLine("Message provided from server :{0}",Encoding.ASCII.GetString(receivedBytes,0,totalBytesReceived)); 17 sender.Shutdown(SocketShutdown.Both); 18 sender.Close(); 19 Console.ReadKey();
6.6Websocket
Websocket协议用于完全双工的通信,一般在浏览器和服务器之间通信。
1 <!doctype html> 2 <head> 3 <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 4 <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script> 5 <title>WroxChat</title> 6 <script type="text/javascript"> 7 $(document).ready(function () { 8 var name = prompt(‘what is your name?:‘); 9 var url = ‘ws://localhost/ws.ashx?name=‘ + name; 10 ws = new WebSocket(url); 11 ws.onopen = function () { 12 $(‘#messages‘).prepend(‘Connected <br/>‘); 13 $(‘#cmdSend‘).click(function () { 14 ws.send($(‘#txtMessage‘).val()); 15 $(‘#txtMessage‘).val(‘‘); 16 }); 17 }; 18 ws.onmessage = function (e) { 19 $(‘#chatMessages‘).prepend(e.data + ‘<br/>‘); 20 }; 21 $(‘#cmdLeave‘).click(function () { 22 ws.close(); 23 }); 24 ws.onclose = function () { 25 $(‘#chatMessages‘).prepend(‘Closed <br/>‘); 26 }; 27 ws.onerror = function (e) { 28 $(‘#chatMessages‘).prepend(‘Oops something went wront <br/>‘); 29 }; 30 }); 31 </script> 32 </head> 33 <body> 34 <input id="txtMessage" /> 35 <input id="cmdSend" type="button" value="Send" /> 36 <input id="cmdLeave" type="button" value="Leave" /> 37 <br /> 38 <div id="chatMessages" /> 39 </body>
1 public class ws : IHttpHandler 2 { 3 4 public void ProcessRequest(HttpContext context) 5 { 6 if (context.IsWebSocketRequest) 7 { 8 var chatuser = new ChatUser(); 9 chatuser.UserName = context.Request.QueryString["name"]; 10 ChatApp.AddUser(chatuser); 11 context.AcceptWebSocketRequest(chatuser.HandleWebSocket); 12 13 } 14 15 } 16 17 public bool IsReusable 18 { 19 get 20 { 21 return false; 22 } 23 } 24 } 25 public class ChatApp 26 { 27 static IList<ChatUser> _users = new List<ChatUser>(); 28 29 public static void AddUser(ChatUser chatUser) 30 { 31 _users.Add(chatUser); 32 foreach(var user in _users) 33 { 34 user.SendMessage(chatUser.UserName + " joined the chat!"); 35 } 36 } 37 38 public static void BroadcastMessage(string message) 39 { 40 foreach (var user in _users) 41 { 42 user.SendMessage(message); 43 } 44 } 45 } 46 public class ChatUser 47 { 48 WebSocketContext _context; 49 public string UserName { get; set; } 50 51 public async Task HandleWebSocket(WebSocketContext wsContext) 52 { 53 _context = wsContext; 54 const int maxMessageSize = 1024; 55 byte[] receiveBuffer = new byte[maxMessageSize]; 56 WebSocket socket = _context.WebSocket; 57 58 while (socket.State == WebSocketState.Open) 59 { 60 WebSocketReceiveResult receiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None); 61 62 if (receiveResult.MessageType == WebSocketMessageType.Close) 63 { 64 await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); 65 } 66 else if (receiveResult.MessageType == WebSocketMessageType.Binary) 67 { 68 await socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept binary frame", CancellationToken.None); 69 } 70 else 71 { 72 var receivedString = Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count); 73 var echoString = string.Concat(UserName, " said: ", receivedString); 74 ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(echoString)); 75 76 ChatApp.BroadcastMessage(echoString); 77 } 78 } 79 } 80 public async Task SendMessage(string message) 81 { 82 if (_context != null && _context.WebSocket.State == WebSocketState.Open) 83 { 84 var outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message)); 85 await _context.WebSocket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None); 86 } 87 } 88 89 }
标签:
原文地址:http://www.cnblogs.com/ztb123/p/5058713.html