.NET开发

本类阅读TOP10

·NHibernate快速指南(翻译)
·vs.net 2005中文版下载地址收藏
·【小技巧】一个判断session是否过期的小技巧
·VB/ASP 调用 SQL Server 的存储过程
·?dos下编译.net程序找不到csc.exe文件
·通过Web Services上传和下载文件
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·VB.NET实现DirectDraw9 (2) 动画
·VB.NET实现DirectDraw9 (1) 托管的DDraw
·建站框架规范书之——文件命名

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
[ASP.NET]使用C#开发Socket通讯

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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



相关文章

相关软件