虽然思路简单,可是实现起来可真麻烦,因为要用到好多类来实现DNS解析,IP辨别,数据格式变换,解码等,比较烦呢
用到了System.Text.Encoding
System.Net.Dns
System.Net.Sockets.Socket
System.Net.IPHostEntry
System.Net.IPAddress
System.Net.IPEndPoint
..
是不是很麻烦?下面的代码运用Socket建立加接,然后朝目标计算机的指定端口发送GET请求,然后将请求返回的头256数据返回

using System;
using System.Net.Sockets;
using System.Net;
using System.Text;

namespace MyControl
{
    
/// <summary>
    
/// SocketTest 的摘要说明。
    
/// </summary>

    public class SocketTest
    
{
        
public SocketTest()
        
{
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//            
        }

        
/// <summary>
        
/// 连接SOCKET
        
/// </summary>
        
/// <param name="Server">服务器名</param>
        
/// <param name="Port">端口</param>
        
/// <returns></returns>

        private  Socket Connection(string Server,int Port)
        
{
            Socket HttpSocket
=null;
            IPHostEntry HostIp
=null;
            HostIp
=Dns.Resolve(Server);
            
foreach(IPAddress TempIp in HostIp.AddressList)
            
{
                IPEndPoint Iep
=new IPEndPoint(TempIp,Port);
                Socket TempSocket
=new Socket(Iep.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
                TempSocket.Connect(Iep);
                
if(TempSocket.Connected)
                
{
                    HttpSocket
=TempSocket;
                    
break;
                }

                
else
                
{
                    
continue;
                }

            }

            
return(HttpSocket);
        }


        
public string GetHomePageByeSocket(string Server,int Port)
        
{
            
string strHomePage=null;
            Encoding AscEncode
=Encoding.ASCII;
            
string strGetString="GET / HTTP/1.1\r\nHost: "+Server+"\r\nConnection: Close\r\n\r\n";
            Byte [] BtGetByte
=AscEncode.GetBytes(strGetString);
            Byte [] BtRevByte
=new Byte[256];

            Socket HttpSocket
=Connection(Server,Port);
            
if(HttpSocket==null)
            
{
                
return("Connection Fail!");
            }

            HttpSocket.Send(BtGetByte,BtGetByte.Length,SocketFlags.None);

            Int32 IntRevByte
=HttpSocket.Receive(BtRevByte,BtRevByte.Length,SocketFlags.None);
            
            strHomePage
+=AscEncode.GetString(BtRevByte,0,IntRevByte);
            
return(strHomePage);
        }

    }

}