下面的示例显示如何使用Socket类向HTTP服务器发送数据和接收响应。
[C#]
publicstringDoSocketGet(stringserver)
{
//Setsupvariablesandastringtowritetotheserver
EncodingASCII=Encoding.ASCII;
stringGet="GET/HTTP/1.1rnHost:"+server+
"rnConnection:Closernrn";
Byte[]ByteGet=ASCII.GetBytes(Get);
Byte[]RecvBytes=newByte[256];
StringstrRetPage=null;
//IPAddressandIPEndPointrepresenttheendpointthatwill
//receivetherequest.
//GetthefirstIPAddressinthelistusingDNS.
IPAddresshostadd=Dns.Resolve(server).AddressList[0];
IPEndPointEPhost=newIPEndPoint(hostadd,80);
//CreatestheSocketforsendingdataoverTCP.
Sockets=newSocket(AddressFamily.InterNetwork,SocketType.Stream,
ProtocolType.Tcp);
//ConnectstothehostusingIPEndPoint.
s.Connect(EPhost);
if(!s.Connected)
{
strRetPage="Unabletoconnecttohost";
returnstrRetPage;
}
//SendstheGETtexttothehost.
s.Send(ByteGet,ByteGet.Length,SocketFlags.None);
//Receivesthepage,loopinguntilallbytesarereceived
Int32bytes=s.Receive(RecvBytes,RecvBytes.Length,0);
strRetPage="DefaultHTMLpageon"+server+":rn";
strRetPage=strRetPage+ASCII.GetString(RecvBytes,0,bytes);
while(bytes>0)
{
bytes=s.Receive(RecvBytes,RecvBytes.Length,SocketFlags.None);
strRetPage=strRetPage+ASCII.GetString(RecvBytes,0,bytes);
}
//如果想立即关闭连接则调用s.Close();
returnstrRetPage;
}