public partial class frmGetContent : Form
{
int port = 80;
string ipStr = "127.0.0.1";
//IPHostEntry ipHostInfo; //主机信息
//IPAddress[] ipList;//IP地址列表
IPAddress ipAddress;
//远程终结点
IPEndPoint ipendpoint;
//Socket实例
Socket socket;
public frmGetContent()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
try
{
//ipHostInfo = Dns.GetHostByName("yesdnn.com");
//ipList = ipHostInfo.AddressList;
ipAddress = IPAddress.Parse(ipStr);
//远程终结点
ipendpoint = new IPEndPoint(ipAddress, port);
//创建socket实例
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//尝试链接
//socket.Connect(ipAddress, port);
socket.Connect(ipendpoint);
//发送给远程主机的请求内容串
string sendStr="GET / HTTP/1.1\r\n Host:mzq \r\n Connection: Close\r\n\r\n";
//sendStr = "GET / HTTP/1.1\r\nHost:mzq \r\n";
//创建byte[] 字节数组 转换发送字符串
byte[] bytesendStr = new byte[1024];
//将发送内容字符串转换为字节byte数组
bytesendStr = Encoding.ASCII.GetBytes(sendStr);
//向主机发送请求
socket.Send(bytesendStr, bytesendStr.Length, SocketFlags.None);
//声明返回内容
string recvStr="";
//声明数组接受长度为1024的byte[]
byte[] byteRecvStr = new byte[1024];
//返回实际接收内容的字节数
//返回 实际接受内容的字节数
int bytes=0;
//循环读取直到数据读取完
while(true )
{
bytes = socket .Receive(byteRecvStr,byteRecvStr.Length , SocketFlags.None );
if(bytes<=0)
{
break ;
}
//将读取的数据流转换为字符串
recvStr += Encoding.ASCII.GetString(byteRecvStr,0,byteRecvStr.Length );
}
this.richTextBox1.Text = recvStr;
//双方都禁止
socket.Shutdown(SocketShutdown.Both);
//关闭
socket.Close();
//保存文件
//将所读取的字符串转换为字节数组
string fileName = "D:\\aaa.htm";
byte[] content=Encoding.ASCII.GetBytes(recvStr);
try {
//创建文件流对象实例
FileStream fs=new FileStream(fileName,FileMode.OpenOrCreate,FileAccess.ReadWrite);
//写入文件
fs.Write(content,0,content.Length);
fs.Close();
fs.Dispose();
}
catch(Exception fe)
{
MessageBox.Show("文件创建/写入错误:"+fe.Message,"提示信息",MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);
}
禁用Socket
//socket.Shutdown(SocketShutdown.Both);
关闭Socket
//socket.Close();
MessageBox.Show("OK");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message );
}
}
}