栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

[C#] 
public string DoSocketGet(string server) 

//Sets up variables and a string to write to the server 
Encoding ASCII = Encoding.ASCII; 
string Get = "GET / HTTP/1.1rnHost: " + server + 
"rnConnection: Closernrn"; 
Byte[] ByteGet = ASCII.GetBytes(Get); 
Byte[] RecvBytes = new Byte[256]; 
String strRetPage = null; 

// IPAddress and IPEndPoint represent the endpoint that will 
// receive the request. 
// Get the first IPAddress in the list using DNS. 
IPAddress hostadd = Dns.Resolve(server).AddressList[0]; 
IPEndPoint EPhost = new IPEndPoint(hostadd, 80); 

//Creates the Socket for sending data over TCP. 
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 
ProtocolType.Tcp ); 

// Connects to the host using IPEndPoint. 
s.Connect(EPhost); 
if (!s.Connected) 

strRetPage = "Unable to connect to host"; 
return strRetPage; 


// Sends the GET text to the host. 
s.Send(ByteGet, ByteGet.Length, SocketFlags.None); 

// Receives the page, looping until all bytes are received 
Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0); 
strRetPage = "Default HTML page on " + 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(); 
return strRetPage; 
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/127919.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号