C# 使用socket访问网页

C#用socket请求网页。

封装类:

public class WebLib{
		public enum MethodType{
			getMethod,
			postMethod
		}
		public struct Rtn{
			public Int16 Code;
			public string Message;
			public string Parameters;
		}
		private Rtn rtn = new Rtn();
		private Socket? socket;
		public string url = "";
		public string host = "";
		public UInt16 port = 80;
		
		public String cookie = "";
		public String referer = "";
		public String postData = "";
		public MethodType methodType;
		public string result = "";
		public string contentType = "application/x-www-form-urlencoded";
		public string uag ="application/x-www-form-urlencoded\"\r\n\tPublic uag As String = \"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Mobile Safari/537.36";
		public WebLib(){
			rtn.Code = 0;
			rtn.Message = "unknown";
		}
		public void WebRequest(){
			Thread t1 = new Thread(web_request);
			t1.IsBackground = true;
			t1.Start();
			t1.Join();
		}
		private void web_request() {
			postData = "";
			string ipStr = this.getIP(host);
			if(ipStr != "") {
				Rtn connect = this.connect(ipStr, port);
				if (connect.Code > 0){
					this.SendData();
				} else {
					Debug.Print("连接失败了,原因为:" + connect.Message);
				}
			} else{
				Debug.Print("无法得到服务器IP地址");
			}
		}

		private Rtn connect(string ip, UInt16 port) {
			socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
			if(socket == null){
				rtn.Code = -1;
				rtn.Message = "连接不上";
				rtn.Parameters=("ip" + ip + ",port=" + port.ToString());
			}
			IPAddress ipaddr = IPAddress.Parse(ip);
			IPEndPoint endPoint = new IPEndPoint(ipaddr, port); // 用指定的ip和端口号初始化IPEndPoint实例
			try{
				socket.Connect(endPoint);
				rtn.Code = 1;
				rtn.Message = "恭喜,连接成功";
			} catch(Exception e){
				rtn.Code = -2;
				rtn.Message = e.Message;
			}
			return rtn;
		}
		private void ReceiveData(){
			byte[] finalbyte = Array.Empty();
			string recvStr;
			byte[] recvBytes = new byte[8192];
			int bytes;
			while(true) {
				bytes = socket.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
				if(bytes > 0){
					Debug.Print("bytes=" + bytes);
					byte[] data_tmp = new byte[bytes];
					Array.Copy(recvBytes, 0, data_tmp, 0, bytes);
					finalbyte = JoinArr(finalbyte, data_tmp);
				} else {
					Debug.Print ("recv_complete");
					recvStr = Encoding.UTF8.GetString(finalbyte);
					result = recvStr;
					break;
				}
			}
		}
		private void SendData() {
			Thread c_thread = new Thread(ReceiveData);
			c_thread.IsBackground = true;
			c_thread.Start();
			if(methodType == MethodType.getMethod) {
				string Data = "GET " + url + " HTTP/1.0" + "\n" +
					"Cookie: " + cookie  + "\n" +
					"User-Agent: " + uag + "\n" +
					"Host: " + host + "\n" + "\n" +
					"Accept-Encoding: gzip, deflate" + "\n" +
					"Accept-Language: en-US" + "\n" +
					"Referer: " + referer;
				Byte[] byteArray = Encoding.Default.GetBytes (Data);
				if(socket != null) {
					Debug.Print("sending");
					socket.Send(byteArray);
				}
			}
			c_thread.Join();
		}

		private byte[] JoinArr(byte[] a, byte[] b) {
			byte[] byteFinal;
			byteFinal = new byte[a.Length + b.Length];
			Array.Copy(a, 0, byteFinal, 0, a.Length);
			Array.Copy(b, 0, byteFinal, a.Length, b.Length);
			return byteFinal;
		}

		public string getIP(string host) {
			try {
				IPHostEntry IpEntry = Dns.GetHostEntry(host);
				for(int i = 0; i < IpEntry.AddressList.Length; i++) {
					//AddressFamily.InterNetwork=IPv4,AddressFamily.InterNetworkV6=IPv6
					if(IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) {
						return IpEntry.AddressList[i].ToString();
					}
				}
			} catch(Exception) {
				
			}
			return "";
		}
	}

调用方法:

public static void Main(string[] args) {
			WebLib obj = new WebLib ();
			obj.host = "这是域名";
			obj.url = "/这里是要访问的地址。去掉域名剩下的";
			obj.port = 80;
			obj.methodType = WebLib.MethodType.getMethod;
			obj.WebRequest();
			Debug.Print("result=" + obj.result);//这是最终结果
		}

 

你可能感兴趣的:(c#,服务器,网络)