C # network programming Overview (3)

Source: Internet
Author: User

Finally, I will show you a good example based on the above C # network programming knowledge. This instance is a client application using Socket based on synchronization mode. It first establishes an end point by parsing the Server IP address and creates a Socket connection based on Streaming Socket, the protocol used is TCP. Through this Socket, you can send the command to get the web page, use this Socket to get the default web page on the server, and write the obtained data to the local file through the file stream. In this way, the web page download is completed. The program running effect is as follows:

Source code: (the main function is DoSocketGet ())

Using System;

Using System. Drawing;

Using System. Collections;

Using System. ComponentModel;

Using System. Windows. Forms;

Using System. Data;

Using System. Net;

Using System. Net. Sockets;

Using System. Text;

Using System. IO;

Namespace SocketSample

{

///

/// Summary of Form1.

///

Public class Form1: System. Windows. Forms. Form

{

Private System. Windows. Forms. Label label1;

Private System. Windows. Forms. Label label2;

Private System. Windows. Forms. Button Download;

Private System. Windows. Forms. TextBox ServerAddress;

Private System. Windows. Forms. TextBox Filename;

///

/// Required designer variables.

///

Private System. ComponentModel. Container components = null;

Public Form1 ()

{

//

// Required for Windows Form Designer support

//

InitializeComponent ();

//

// TODO: add Any constructor code after InitializeComponent calls

//

}

///

/// Clear all resources in use.

///

Protected override void Dispose (bool disposing)

{

If (disposing)

{

If (components! = Null)

{

Components. Dispose ();

}

}

Base. Dispose (disposing );

}

# Region Windows Form Designer generated code

///

/// The designer supports the required methods-do not use the code editor to modify

/// Content of this method.

///

Private void InitializeComponent ()

{

This. label1 = new System. Windows. Forms. Label ();

This. label2 = new System. Windows. Forms. Label ();

This. Download = new System. Windows. Forms. Button ();

This. ServerAddress = new System. Windows. Forms. TextBox ();

This. Filename = new System. Windows. Forms. TextBox ();

This. SuspendLayout ();

//

// Label1

//

This. label1.Location = new System. Drawing. Point (16, 24 );

This. label1.Name = "label1 ";

This. label1.Size = new System. Drawing. Size (80, 23 );

This. label1.TabIndex = 0;

This. label1.Text = "server address :";

This. label1.TextAlign = System. Drawing. ContentAlignment. MiddleRight;

//

// Label2

//

This. label2.Location = new System. Drawing. Point (16, 64 );

This. label2.Name = "label2 ";

This. label2.Size = new System. Drawing. Size (80, 23 );

This. label2.TabIndex = 1;

This. label2.Text = "local file name :";

This. label2.TextAlign = System. Drawing. ContentAlignment. MiddleRight;

//

// Download

//

This. Download. Location = new System. Drawing. Point (288, 24 );

This. Download. Name = "Download ";

This. Download. TabIndex = 2;

This. Download. Text = "Start Download ";

This. Download. Click + = new System. EventHandler (this. Download_Click );

//

// ServerAddress

//

This. ServerAddress. Location = new System. Drawing. Point (96, 24 );

This. ServerAddress. Name = "ServerAddress ";

This. ServerAddress. Size = new System. Drawing. Size (176, 21 );

This. ServerAddress. TabIndex = 3;

This. ServerAddress. Text = "";

//

// Filename

//

This. Filename. Location = new System. Drawing. Point (96, 64 );

This. Filename. Name = "Filename ";

This. Filename. Size = new System. Drawing. Size (176, 21 );

This. Filename. TabIndex = 4;

This. Filename. Text = "";

//

// Form1

//

This. AutoScaleBaseSize = new System. Drawing. Size (6, 14 );

This. ClientSize = new System. Drawing. Size (376,117 );

This. Controls. AddRange (new System. Windows. Forms. Control [] {

This. Filename,

This. ServerAddress,

This. Download,

This. label2,

This. label1 });

This. Name = "Form1 ";

This. Text = "webpage downloader ";

This. ResumeLayout (false );


}

# Endregion

///

/// Main entry point of the application.

///

[STAThread]

Static void Main ()

{

Application. Run (new Form1 ());

}

Private string DoSocketGet (string server)

{

File: // setNecessary variables and a string to be sent to the server

Encoding ASCII = Encoding. ASCII;

String Get = "GET/HTTP/1.1 Host:" + server +

"Connection: Close ";

Byte [] ByteGet = ASCII. GetBytes (Get );

Byte [] RecvBytes = new Byte [1, 256];

String strRetPage = null;

File: // getTake the list of IP addresses related to the server. The first one is

IPAddress hostadd = Dns. Resolve (server). AddressList [0];

File: // RootCreate an endpoint for the IP address of the obtained server. The default port is 80.

IPEndPoint EPhost = new IPEndPoint (hostadd, 80 );

File: // createCreate a Socket instance

Socket s = new Socket (AddressFamily. InterNetwork, SocketType. Stream,

ProtocolType. Tcp );


Try

{

File: //Connect the obtained endpoint to the server

S. Connect (EPhost );

}

Catch (Exception se)

{

MessageBox. Show ("connection error:" + se. Message, "prompt Message ",

MessageBoxButtons. RetryCancel, MessageBoxIcon. Information );

}


If (! S. Connected)

{

StrRetPage = "cannot connect to the server! ";

Return strRetPage;

}


Try

{

File: //The server sends the GET command

S. Send (ByteGet, ByteGet. Length, SocketFlags. None );

}

Catch (Exception ce)

{

MessageBox. Show ("sending error:" + ce. Message, "prompt Message ",

MessageBoxButtons. RetryCancel, MessageBoxIcon. Information );

}


File: // connectCollect page data until all bytes are received

Int32 bytes = s. Receive (RecvBytes, RecvBytes. Length, 0 );

StrRetPage = "The following is the default webpage on the server" + server + :";

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 );

}

File: // disabledUse and disable Socket instances

S. Shutdown (SocketShutdown. Both );

S. Close ();

 

Return strRetPage;

}

Private void Download_Click (object sender, System. EventArgs e)

{

File: // setConverts the read string to a byte array.

Byte [] content = Encoding. ASCII. GetBytes (DoSocketGet (ServerAddress. Text ));

Try

{

File: // create

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.