使用C#开发Socket通讯的方法
发布日期:2022-02-05 18:27:43 浏览次数:13 分类:技术文章

本文共 1402 字,大约阅读时间需要 4 分钟。

下面的示例显示如何使用 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.1/r/nHost: " + server +
"/r/nConnection: Close/r/n/r/n";
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 + ":/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();
return strRetPage;
}

转载地址:https://blog.csdn.net/lisong58420/article/details/2453669 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Javascript的Event对象详解[收集整理]
下一篇:C#的四个基本技巧

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年03月31日 14时27分45秒