C # Network Programming

Source: Internet
Author: User
Tags getstream

One of the differences between C # And C ++ is that C # does not have a class library. The class library used is the class library in the. Net FrameWork --. Net FrameWork SDK. The. Net FrameWork SDK provides two namespaces for network programming: "System. Net" and "System. Net. Sockets ". C # implements network communication through the classes and Methods encapsulated in the two namespaces.

First, let's explain several concepts that we often encounter in network programming: synchronous, asynchronous, Block, and Unblock ):

The synchronous Mode means that after the sender sends a data packet, the sender sends the next data packet without waiting for the response from the receiver. Asynchronous mode means that after the sender sends a data packet, the next data packet is sent until the receiver responds. Blocking Socket means that the network call of this socket will not be returned until the call is successful. Otherwise, this set of characters will be blocked on the network call, such as calling Readlin () of the StreamReader class () method to read data in the network buffer. If no data arrives during the call, the Readlin () method will be mounted on the call until you read some data; A non-blocking Socket means that the network call of the socket is returned immediately no matter whether the call is successful or not. Similarly, the Readlin () method of the StreamReader class is called to read data in the network buffer. no matter whether the data is read or not, it is immediately returned and will not always be attached to this function call. In the development of Windows Network Communication Software, the most common method is asynchronous non-blocking socket. Normally, the C/S (Client/Server) structure software adopts the asynchronous non-blocking mode.

In fact, in network programming with C #, we do not need to understand the principles and working mechanisms of synchronization, Asynchronization, blocking, and non-blocking, because in. these mechanisms have been encapsulated in the Net FrameWrok SDK. Next we will use C # To open a specific network program to illustrate a problem.

I. program design and running environment described in this article

(1). Microsoft Windows 2000 Server Edition

(2). Net Framework SDK Beta 2 or later

II. Key Steps for server-side program design and solutions:

In the program accepted below, we adopt the asynchronous blocking method.

(1) first, you must create a "tcpListener" object on the given port to listen to requests on the network. After receiving a connection request, call the "AcceptSocket" method of the "tcpListener" object to generate an instance of the Socket used to process the connection request. The specific implementation code is as follows:

// Create a tcpListener object, which listens on the specified port.
TcpListener = new TcpListener (1234 );
// Start listening
TcpListener. Start ();
// Return the Socket instance that can be used to process the connection
SocketForClient = tcpListener. AcceptSocket ();

(2). Accept and send client data:

At this time, the Socket instance has been generated. If there is a request on the network, after the request passes, the Socket instance constructs a "NetworkStream" object, and the "NetworkStream" Object provides the basic data stream for network access. We use the two classes "StreamReader" and "StreamWriter" encapsulated in the namespace "System. IO" to access the "NetworkStream" object. The ReadLine () method in the "StreamReader" class reads a line of characters from the "NetworkStream" object; the WriteLine () method in the "StreamWriter" Class () the method is to write a line of string to the "NetworkStream" object. To transmit strings over the network, the specific implementation code is as follows:

Try
{
// If the returned value is "true", the resulting character set has accepted connection requests from far away.
If (socketForClient. Connected)
{
ListBox1.Items. Add ("You have successfully connected to the client! ");
While (true)
{
// Create a networkStream object to accept and send data through the network set of characters
NetworkStream = new NetworkStream (socketForClient );
// Read a line of characters from the current data stream. The returned value is a string.
StreamReader = new StreamReader (networkStream );
String msg = streamReader. ReadLine ();
ListBox1.Items. Add ("received client information:" + msg );
StreamWriter = new StreamWriter (networkStream );
If (textBox1.Text! = "")
{
ListBox1.Items. Add ("feedback to the client:" + textBox1.Text );
// Write a line of string to the current data stream
StreamWriter. WriteLine (textBox1.Text );
// Refresh the data in the current data stream
StreamWriter. Flush ();
}
}
}
}
Catch (Exception ey)
{
MessageBox. Show (ey. ToString ());
}

(3) Don't forget to close the stream, stop listening to the network, and close the set of characters, as shown below:

// Close the thread and stream
NetworkStream. Close ();
StreamReader. Close ();
StreamWriter. Close ();
_ Thread1.Abort ();
TcpListener. Stop ();
SocketForClient. Shutdown (SocketShutdown. Both );
SocketForClient. Close ();
III. C # part of the source code of the network programming server program (server. cs ):

Because the structure we adopt in this program is asynchronous blocking mode, in the actual program, in order not to affect the running speed of the server-side program, we designed a thread in the program, make the network request listening, receiving, and sending processes in the thread. Please note this in the following code. The following is the server. complete cs code:

Using System;
Using System. Drawing;
Using System. Collections;
Using System. ComponentModel;
Using System. Windows. Forms;
Using System. Data;
Using System. Net. Sockets;
Using System. IO;
Using System. Threading;
Using System. Net;
// The namespace used in the import program
Public class Form1: Form
{
Private ListBox ListBox1;
Private Button button2;
Private Label label1;
Private TextBox textBox1;
Private Button button1;
Private Socket socketForClient;
Private NetworkStream networkStream;
Private TcpListener tcpListener;
Private StreamWriter streamWriter;
Private StreamReader streamReader;
Private Thread _ thread1;
Private System. ComponentModel. Container components = null;
Public Form1 ()
{
InitializeComponent ();
}
// Clear various resources used in the program
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
Private void InitializeComponent ()
{
Label1 = new Label ();
Button2 = new Button ();
Button1 = new Button ();
ListBox1 = new ListBox ();
TextBox1 = new TextBox ();
SuspendLayout ();
Label1.Location = new Point (8,168 );
Label1.Name = "label1 ";
Label1.Size = new Size (120, 23 );
Label1.TabIndex = 3;
Label1.Text = "feedback to the client :";
// Set other controls in the same way, skipped here

This. Controls. Add (button1 );
This. Controls. Add (textBox1 );
This. Controls. Add (label1 );
This. Controls. Add (button2 );
This. Controls. Add (ListBox1 );
This. MaximizeBox = false;
This. MinimizeBox = false;
This. Name = "Form1 ";
This. Text = "C # network programming server! ";
This. Closed + = new System. EventHandler (this. Form1_Closed );
This. ResumeLayout (false );

}
Private void Listen ()
{
// Create a tcpListener object, which listens on the specified port.
TcpListener = new TcpListener (1234 );
// Start listening
TcpListener. Start ();
// Return the Socket instance that can be used to process the connection
SocketForClient = tcpListener. AcceptSocket ();
Try
{
// If the returned value is "true", the resulting character set has accepted connection requests from far away.
If (socketForClient. Connected)
{
ListBox1.Items. Add ("You have successfully connected to the client! ");
While (true)
{
// Create a networkStream object to accept and send data through the network set of characters
NetworkStream = new NetworkStream (socketForClient );
// Read a line of characters from the current data stream. The returned value is a string.
StreamReader = new StreamReader (networkStream );
String msg = streamReader. ReadLine ();
ListBox1.Items. Add ("received client information:" + msg );
StreamWriter = new StreamWriter (networkStream );
If (textBox1.Text! = "")
{
ListBox1.Items. Add ("feedback to the client:" + textBox1.Text );
// Write a line of string to the current data stream
StreamWriter. WriteLine (textBox1.Text );
// Refresh the data in the current data stream
StreamWriter. Flush ();
}
}
}
}
Catch (Exception ey)
{
MessageBox. Show (ey. ToString ());
}
}
Static void Main ()
{
Application. Run (new Form1 ());
}

Private void button#click (object sender, System. EventArgs e)
{
ListBox1.Items. Add ("the service has been started! ");
_ Thread1 = new Thread (new ThreadStart (Listen ));
_ Thread1.Start ();

}

Private void button2_Click (object sender, System. EventArgs e)
{
// Close the thread and stream
NetworkStream. Close ();
StreamReader. Close ();
StreamWriter. Close ();
_ Thread1.Abort ();
TcpListener. Stop ();
SocketForClient. Shutdown (SocketShutdown. Both );
SocketForClient. Close ();
}
Private void formpolicclosed (object sender, System. EventArgs e)
{
// Close the thread and stream
NetworkStream. Close ();
StreamReader. Close ();
StreamWriter. Close ();
_ Thread1.Abort ();
TcpListener. Stop ();
SocketForClient. Shutdown (SocketShutdown. Both );
SocketForClient. Close ();
}
}

4. Key Steps for client program design and solutions:

(1). Specify the port connecting to the server:

The local machine we use is both a server and a client. You can modify the IP address to determine the server you want to connect. We used the "TcpClient" class during the connection. This class provides TCP services at a higher abstraction level (higher than the Socket class. The following code connects to the Local Machine (Port 1234) and obtains the response stream:

// Connect to the server port. Here, the local machine is used as the server. You can change the server by modifying the IP address.
Try
{
Myclient = new TcpClient ("localhost", 1234 );
}
Catch
{
MessageBox. Show ("not connected to the server! ");
Return;
}
// Create a networkStream object to accept and send data through the network set of characters
NetworkStream = myclient. GetStream ();
StreamReader = new StreamReader (networkStream );
StreamWriter = new StreamWriter (networkStream );

(2). To accept and send data:

We still use the "NetworkStream" class to accept and send data, because it is relatively simple to operate on it. Whether to send and accept data through the namespace "System. the ReadLine () method of the "StreamReader" class in IO "and the WriteLine () method of the" StreamWriter "class. The specific implementation method is as follows:

If (textBox1.Text = "")
{
MessageBox. Show ("Please make sure the text box is not empty! ");
TextBox1.Focus ();
Return;
}
Try
{
String s;
// Write a line of string to the current data stream
StreamWriter. WriteLine (textBox1.Text );
// Refresh the data in the current data stream
StreamWriter. Flush ();
// Read a line of characters from the current data stream. The returned value is a string.
S = streamReader. ReadLine ();
ListBox1.Items. Add ("read the content sent by the server:" + s );
}
Catch (Exception ee)
{
MessageBox. Show ("An error occurred while reading data from the server. Type:" + ee. ToString ());
}

(3). The last step is the same as that on the server side. It is to close the stream created in the program, as shown below:

StreamReader. Close ();
StreamWriter. Close ();
NetworkStream. Close ();
5. Some client code:

Because the client does not need to listen on the network, there is no program blocking on the call, so in the following code, we do not use the thread, this is a difference from a server-side program. To sum up these key steps, you can get a complete client Program (client. cs) programmed using the C # network. The details are as follows:

Using System;
Using System. Drawing;
Using System. Collections;
Using System. ComponentModel;
Using System. Windows. Forms;
Using System. Data;
Using System. Net. Sockets;
Using System. IO;
Using System. Threading;
// The namespace used in the import program
Public class Form1: Form
{
Private ListBox ListBox1;
Private Label label1;
Private TextBox textBox1;
Private Button button3;
Private NetworkStream networkStream;
Private StreamReader streamReader;
Private StreamWriter streamWriter;
TcpClient myclient;
Private Label label2;

Private System. ComponentModel. Container components = null;

Public Form1 ()
{
InitializeComponent ();
}
// Clear various resources used in the program
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
Private void InitializeComponent ()
{
Label1 = new Label ();
Button3 = new Button ();
ListBox1 = new ListBox ();
TextBox1 = new TextBox ();
Label2 = new Label ();
SuspendLayout ();
Label1.Location = new Point (8,168 );
Label1.Name = "label1 ";
Label1.Size = new Size (56, 23 );
Label1.TabIndex = 3;
Label1.Text = "information :";
// Set other controls in the same way
AutoScaleBaseSize = new Size (6, 14 );
ClientSize = new Size (424,205 );
This. Controls. Add (button3 );
This. Controls. Add (textBox1 );
This. Controls. Add (label1 );
This. Controls. Add (label2 );
This. Controls. Add (ListBox1 );
This. MaximizeBox = false;
This. MinimizeBox = false;
This. Name = "Form1 ";
This. Text = "C # network programming client! ";
This. Closed + = new System. EventHandler (this. Form1_Closed );
This. ResumeLayout (false );
// Connect to the server port. Here, the local machine is used as the server. You can change the server by modifying the IP address.
Try
{
Myclient = new TcpClient ("localhost", 1234 );
}
Catch
{
MessageBox. Show ("not connected to the server! ");
Return;
}
// Create a networkStream object to accept and send data through the network set of characters
NetworkStream = myclient. GetStream ();
StreamReader = new StreamReader (networkStream );
StreamWriter = new StreamWriter (networkStream );
}
Static void Main ()
{
Application. Run (new Form1 ());
}

Private void button3_Click (object sender, System. EventArgs e)
{

If (textBox1.Text = "")
{
MessageBox. Show ("Please make sure the text box is not empty! ");
TextBox1.Focus ();
Return;
}
Try
{
String s;
// Write a line of string to the current data stream
StreamWriter. WriteLine (textBox1.Text );
// Refresh the data in the current data stream
StreamWriter. Flush ();
// Read a line of characters from the current data stream. The returned value is a string.
S = streamReader. ReadLine ();
ListBox1.Items. Add ("read the content sent by the server:" + s );
}
Catch (Exception ee)
{
MessageBox. Show ("An error occurred while reading data from the server. Type:" + ee. ToString ());
}
}

Private void formpolicclosed (object sender, System. EventArgs e)
{
StreamReader. Close ();
StreamWriter. Close ();
NetworkStream. Close ();

}
}

VII. Summary:

Although in. net FrameWrok SDK only provides two namespaces for network programming, but the content in these two namespaces is very rich, C # using these two namespaces can both implement synchronization and Asynchronization, as well as implement blocking and non-blocking. This article uses C # To compile a program for information transmission on the network to show its rich content. Due to the limited length, deeper, and more powerful features, readers need to practice and explore.

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.