1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms;10 using System.Net.Sockets;11 using System.Net;12 13 namespace WindowsFormsApplication514 {15 public partial class Form1 : Form16 {17 public Form1()18 {19 InitializeComponent();20 }21 private static Socket ConnectSocket(string server, int port)22 {23 Socket socket = null;24 IPHostEntry iphostentry = null;25 iphostentry = Dns.GetHostEntry(server);26 foreach(IPAddress address in iphostentry.AddressList)27 {28 IPEndPoint IPEPoint = new IPEndPoint(address,port);29 Socket newSocket = new Socket(IPEPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);30 newSocket.Connect(IPEPoint);31 if(newSocket.Connected)32 {33 socket = newSocket;34 break;35 }36 else37 {38 continue;39 }40 }41 return socket;42 }43 44 private static string SocketSendReveive(string server, int port)45 {46 string request = "GET/HTTP/1.1\n Host: " + server + "\n connetc: close\n";47 Byte[] btSend = Encoding.ASCII.GetBytes(request);48 Byte[] btReceived = new Byte[256];49 Socket socket = ConnectSocket(server,port);50 if(socket == null)51 return ("connect failed.");52 socket.Send(btSend,btSend.Length,0);53 int intContent = 0;54 string strContent = server + " 's content :\n";55 do56 {57 intContent = socket.Receive(btReceived, btReceived.Length, 0);58 strContent += Encoding.ASCII.GetString(btReceived,0,intContent);59 }60 while(intContent > 0);61 return strContent;62 }63 64 65 66 private void button1_Click(object sender, EventArgs e)67 {68 string server = textBox1.Text;69 int port = Convert.ToInt32(textBox2.Text);70 string strContent = SocketSendReveive(server, port);71 MessageBox.Show(strContent);72 73 }74 }75 }