使用C#开发Socket通讯的方法
使用C#开发Socket通讯的方法
发布时间:2016-12-28 来源:查字典编辑
摘要:下面的示例显示如何使用Socket类向HTTP服务器发送数据和接收响应。[C#]publicstringDoSocketGet(string...

下面的示例显示如何使用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;

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新C#教程学习
热门C#教程学习
编程开发子分类