C#网络通讯方式总结记录
参考代码:https://i.cnblogs.com/EditPosts.aspx?opt=1
1、WebClient同步请求
//实例化 WebClient client = new WebClient(); //地址 string path = "http://127.0.0.1/a/b"; //传递的数据 string datastr = "id=" + System.Web.HttpUtility.UrlEncode(ids); //参数转流 byte[] bytearray = Encoding.UTF8.GetBytes(datastr); //采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可 client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//长度 client.Headers.Add("ContentLength", bytearray.Length.ToString()); //上传,post方式,并接收返回数据(这是同步,需要等待接收返回值) byte[] responseData = client.UploadData(path, "POST", bytearray); //释放,正式项目中,根据具体情况设计需不需要马上释放 client.Dispose(); //处理返回数据(一般用json) string srcString = Encoding.UTF8.GetString(responseData);
2、WebClient异步请求
//绑定事件,获取返回值 client.UploadDataCompleted += new UploadDataCompletedEventHandler(UploadDataCallback2); //这里是url地址 Uri uri = new Uri(url); //异步post提交,不用等待。 client.UploadDataAsync(uri, "POST", bytearray); //接收返回值的方法 public static void UploadDataCallback2(Object sender, UploadDataCompletedEventArgs e) { //接收返回值 byte[] data = (byte[])e.Result; //转码 string reply = Encoding.UTF8.GetString(data); //打印日志 LogResult("返回数据:" + reply + "\n"); }
3、超时时间设置
//需要新写个类继承WebClient,并重写 //然后实例化,就可以设置超时时间了。 例:WebClient webClient = new WebDownload(); /// <summary> /// WebClient 超时设置 /// </summary> public class WebDownload : WebClient { private int _timeout; // 超时时间(毫秒) public int Timeout { get { return _timeout; } set { _timeout = value; } } public WebDownload() { //设置时间 this._timeout = 60000000; } public WebDownload(int timeout) { this._timeout = timeout; } protected override WebRequest GetWebRequest(Uri address) { var result = base.GetWebRequest(address); result.Timeout = this._timeout; return result; } }
4、WebRequest方式
//地址 string url = "http://127.0.0.1/a/b?pro=" + pro; //传的参数 string datastr1 = "id=" + System.Web.HttpUtility.UrlEncode(ids); //转成字节 byte[] bytearray1 = Encoding.UTF8.GetBytes(datastr1); //创建WebRequest HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url); //POST方式 webrequest.Method = "POST"; // <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式) webrequest.ContentType = "application/x-www-form-urlencoded"; //获取字节数 webrequest.ContentLength = Encoding.UTF8.GetByteCount(datastr1); //获取用于写入请求数据的 System.IO.Stream 对象 Stream webstream = webrequest.GetRequestStream(); //向当前流中写入字节序列,并将此流中的当前位置提升写入的字节数。 webstream.Write(bytearray1, 0, bytearray1.Length); //获取返回数据 HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse(); //转码 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //返回的结果 string ret = sr.ReadToEnd(); //关闭 sr.Close(); response.Close(); webstream.Close();
5、Socket异步
发送数据:Socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(SendCallbackHandler), state);
sokcet连接成功后,监视接收数据:socket.BeginReceive(state.Buffer, stateoffset, receiveDataSize - stateoffset,SocketFlags.None, new AsyncCallback(AsyncReceiveCallbackHandler), this.state);
其他通讯方式,可以查询MSDN官方文档。