We know
C #One of the differences with C ++ is that it 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 #Is the classes and Methods encapsulated in the two namespaces.
ImplementationNetwork communication.
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.
Actually in useC #In network programming, we do not need to understand the principles and working mechanisms of synchronization, Asynchronization, blocking, and non-blocking, because these mechanisms have been encapsulated in the. Net FrameWrok SDK. Next we will useC #Open a specific network program to illustrate the 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.ServerKey steps of 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. Below are the specificImplementationCode:
// 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"ImplementationAccess to 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. ThusImplementationTransmit the string on the network.ImplementationCode:
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 #Network ProgrammingServerPart of the source code of the Program (server.Cs):
In this program, the structure we use is asynchronous blocking, so in the actual program, in order not to affectServerWe have designed a thread in the program to listen to, accept, and send network requests. Please pay attention to this in the following code, below is the server.CsComplete 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 ProgrammingServer! ";
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). ConnectServerThe specified port:
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:
// ConnectServerPort. 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 ).ImplementationReceive and send data:
We still use the "NetworkStream" class to accept and send data, because it is relatively simple to operate on it.ImplementationThe sending and receiving methods are also passed through the "StreamReader" class ReadLine () method in the namespace "System. IO" and the WriteLine () method of the "StreamWriter" class. SpecificImplementationThe 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 ("readServerSent content: "+ s );
}
Catch (Exception ee)
{
MessageBox. Show ("fromServerAn error occurred while reading data; Type: "+ ee. ToString ());
}
(3). Last step andServerThe same is true, that is, to close the stream created in the program, as follows:
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, which isServerA difference between programs. Summarize the above key steps to obtainC #Network Programming complete client Program (client.Cs), 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 );
// ConnectServerPort. 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 ("readServerSent content: "+ s );
}
Catch (Exception ee)
{
MessageBox. Show ("fromServerAn error occurred while reading data; Type: "+ ee. ToString ());
}
}
Private void formpolicclosed (object sender, System. EventArgs e)
{
StreamReader. Close ();
StreamWriter. Close ();
NetworkStream. Close ();
}
}
Is the interface to run after compiling the above two programs:
Figure 01:C #Compile the network program running interface
VII. Summary:
Although the. Net FrameWrok SDK only provides two namespaces for network programming, the content of the two namespaces is very rich,C #You can use these two namespacesImplementationSynchronous and asynchronous.ImplementationBlocking and non-blocking. This article usesC #The compilation of a program for information transmission on the network shows its rich content. Due to the limited space, the program is deeper, and more powerful functions still need to be practiced and explored by readers.
Author: Shui mu
Source: http://www.hitidc.com/
Source:
Http://www.cnblogs.com/hsapphire/archive/2010/01/08/1641930.html