usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Net;usingSystem.Net.Sockets;namespacetest06{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } Private StaticSocket Connectsocket (stringServerintPort) {Socket Socket=NULL;//instantiates the socket object and initializes it to an emptyIphostentry Iphostentry =NULL;//instantiates a Iphostentry object and initializes it to an emptyIphostentry = dns.gethostentry (server);//Get host information//Loop through the resulting list of IP addresses foreach(IPAddress AddressinchIphostentry. AddressList) {//instantiates a IPEndPoint object with the specified IP address and port numberIPEndPoint Ipepoint =NewIPEndPoint (address, port); //use the socket's constructor to instantiate a socket object so that it can be used to connect to the remote hostSocket Newsocket =Newsockets (Ipepoint.addressfamily, SocketType.Stream, protocoltype.tcp); Newsocket.connect (Ipepoint); //Call the Connect method to connect to a remote host if(newsocket.connected)//determine if a remote connection is connected{Socket=Newsocket; Break; } Else { Continue; } } returnsocket; } //gets the main page content of the specified server Private Static stringSocketsendreceive (stringServerintPort) { stringRequest ="get/http/1.1\n Host:"+ Server +"\ nthe connection: off \ n"; Byte[] Btsend=Encoding.ASCII.GetBytes (Request); Byte[] btreceived=Newbyte[ the]; //Call custom method Connectsocket to instantiate a socket object with the specified server name and port numberSocket socket =connectsocket (server, port); if(Socket = =NULL) return("Connection Failed! "); //send a request to a connected serverSocket. Send (Btsend, Btsend.length,0); intIntcontent =0; stringstrcontent = Server +"the default page content on: \ n"; Do { //receive data from a bound socketIntcontent = socket. Receive (btreceived, Btreceived.length,0); //convert the received data to a string typeStrcontent + = Encoding.ASCII.GetString (btreceived,0, intcontent); } while(Intcontent >0); returnstrcontent; } Private voidButton1_Click (Objectsender, EventArgs e) { stringServer = TextBox1.Text;//Specify host name intPort = Convert.ToInt32 (TextBox2.Text);//Specify port number//Call the custom method socketsendreceive get the main page content of the specified host stringStrcontent =socketsendreceive (server, port); MessageBox.Show (strcontent); } }}
Socket Class Communication Example-24th chapter