大神,怎样用C#模拟websocket客户端
给你一些建议,模拟登录的。
static CookieContainer GetCookie(string postString, string postUrl)
{
CookieContainer cookie = new CookieContainer();
HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(postUrl);//创建http 请求
httpRequset.CookieContainer = cookie;//设置cookie
httpRequset.Method = "POST";//POST 提交
httpRequset.KeepAlive = true;
httpRequset.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0";
httpRequset.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
httpRequset.ContentType = "application/x-www-form-urlencoded";//以上信息在监听请求的时候都有的直接复制过来
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postString);
httpRequset.ContentLength = bytes.Length;
Stream stream = httpRequset.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();//以上是POST数据的写入
HttpWebResponse httpResponse = (HttpWebResponse)httpRequset.GetResponse();//获得 服务端响应
return cookie;//拿到cookie
}
static string GetContent(CookieContainer cookie, string url)
{
string content;
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.CookieContainer = cookie;
httpRequest.Referer = url;
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0";
httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.Method = "GET";
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (Stream responsestream = httpResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responsestream, System.Text.Encoding.UTF8))
{
content = sr.ReadToEnd();
}
}
return content;
}
private void button1_Click(object sender, EventArgs e)
{
//抓取信息
string loginstr = "";
//从登陆的地址获取cookie
CookieContainer cookie = GetCookie(loginstr, "");
//这个是进入后台地址
//webBrowser1.DocumentText = GetContent(cookie, "");
textBox1.Text = GetContent(cookie, "");
}