[ASP.NET]使用C#开发Socket通讯

该博客给出了使用C#的Socket类向HTTP服务器发送数据并接收响应的示例代码。代码中设置了变量和发送给服务器的字符串,通过Socket连接服务器,发送GET请求并接收页面内容,最后返回响应结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

[C#]
public string DoSocketGet(string server)
{
    //Sets up variables and a string to write to the server
    Encoding ASCII = Encoding.ASCII;//此处如果需要传输中文字串,需要设置成Encoding.Default
    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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值