使用C#开发Socket通讯的方法

时间:2021-05-19

下面的示例显示如何使用Socket类向HTTP服务器发送数据和接收响应。

[C#]
publicstringDoSocketGet(stringserver)
{
//Setsupvariablesandastringtowritetotheserver
EncodingASCII=Encoding.ASCII;
stringGet="GET/HTTP/1.1\r\nHost:"+server+
"\r\nConnection:Close\r\n\r\n";
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+":\r\n";
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;
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章