C # complete example of socket-based CS Mode

Source: Internet
Author: User

in this example, data transmission between multiple clients and servers is established based on the socket server. First, the server is designed. Open vs2008 and create a Program for a Windows application named socketserver under the D: \ C # \ ch17 directory. Open the project and add controls to the current form, as shown in table 17-6.
Table 17-6 Add a control list

Control Module

Name

Text

ListBox

Lbinfo

 

Label

Label

 

Button

Button1

Start the server

The designed interface is 17-2.

Next, we will use the previous knowledge to design the server. The steps are as follows.
(1) first, include some namespaces, including system. net, system. net. sockets, system. Io, and system. threading. Then define a series of global variables, as shown below.
 

 Private Socket S; //  Define a socket object  
Private Thread th; // Client Connection server thread
Public Socket csocket; // Socket object connected to a single client
Public Networkstream ns; // Network Flow
Public Streamreader SR; // Stream reading
Public Streamwriter SW; // Stream writing
Private Delegate Void Settextcallback (); // Used to operate the main program-controlled parts

(2) The next step is to design the management of client connections, mainly including the connection between the server and the client and sending and receiving data. Put them in a function communication, as shown below.

 Public   Void Communication ()
{
While ( True )
{
Try
{
Csocket = S. Accept (); // Use csocket to represent the client connection
If (Csocket. Connected) // Test whether the connection is successful
{
NS = New Networkstream (csocket ); // Create a network stream to facilitate data reading
Sr = New Streamreader (NS );// Instantiate stream read object
Sw = New Streamwriter (NS ); // Instantiate write Stream Object
Test (); // Read from stream
Sw. writeline ( " Receive request, allow connection " ); // Write Data to the stream
Sw. Flush (); // Clear the buffer
}
Else
{
MessageBox. Show ( " Connection Failed " );
}
}
Catch (Socketexception ex)
{
MessageBox. Show (ex. Message ); // Catch socket exceptions
}
Catch (Exception es)
{
MessageBox. Show ( " Other exceptions " + ES. Message ); // Catch other exceptions
}
}
}
// BelowCodeThe usage was mentioned in chapter 16th concerning thread usage. It is mainly used to operate controls in the main thread from the current thread. // Description
Public Void Send ()
{
Lbinfo. Items. Add (Sr. Readline () + " \ N " );
}
Public Void Test ()
{
Settextcallback stcb = New Settextcallback (send );
Invoke (stcb );
}

 

(3) After defining the connection with the client, you need to use the thread to start it. Double-click the "Start server" button and add the following code.
 

Button1.enabled = False ;
S = New Socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP ); // Create a socket object
IPaddress serverip = IPaddress. parse ( " 222.18.142.171 " );
Ipendpoint Server = New Ipendpoint (serverip, 13 ); // Instantiate the Server IP address and port
S. BIND (server );
S. Listen ( 10 );
Try
{
Th = New Thread ( New Threadstart (Communication ));// Create thread
Th. Start (); // Start thread
Label1.text = " Server started successfully! " ;
}
Catch (Exception ex)
{
MessageBox. Show ( " Server startup failed! " + Ex. Message );
}

(4) When closing the server window, you should also close the connection between the thread and the current socket. The Code is as follows.
 

 Protected   Override   Void Dispose ( Bool Disposing)
{
Try
{
If (Disposing & (components! = Null ))
{
Components. Dispose ();
Th. Abort ();
// Disable data sending and receiving in the current socket connection
S. Shutdown (system. net. sockets. socketshutdown. Both );
S. Close ();
}
Base . Dispose (disposing );
}
Catch
{
Return ;
}
}
// Add the following code for the formclosed event of the current form.
This . Close ();

Now, the server has been designed. Next we will look at the client.
Open vs2008 Based on the Socket Client and create a Windows application named socketclient under the D: \ C # \ ch17 directory. Open the project and add controls to the current form, as shown in table 17-7.
Table 17-7 add controls

Control Component name

Name

Text

Groupbox

Groupbox1

Send messages to the server

Label

Label1

Send message:

Textbox

Textbox1

 

Button

Button2

Send

ListBox

Lbinfo

 

Groupbox

Groupbox1

Server feedback information

The design of the client is divided into the following steps.
(1) The first task is to reference some namespaces, as shown below.

 
UsingSystem. IO;
UsingSystem. net. Sockets;
UsingSystem. net;

Then define a series of global variables, as shown below.

 
PrivateSocket S;//Define a socket object
PublicNetworkstream ns;//Network Flow
PublicStreamreader SR;//Stream reading
PublicStreamwriter SW;//Stream writing

(2) Double-click the send button to add the following code.

S = New Socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Serverip = IPaddress. parse ( " 222.18.142.171 " ); // Server IP Address
Try
{
S. Connect (serverip, 13 ); // Connect to the server. The port number is 13.
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
Try
{
NS = New Networkstream (s ); // Instantiate a network stream
Sr = New Streamreader (NS ); // Instantiate stream read object
Sw = New Streamwriter (NS ); // Instantiate write Stream Object
Sw. writeline (textbox1.text ); // Write textbox1.text data to the stream
Sw. Flush (); // Clear the buffer
Lbinfo. Items. Add (Sr. Readline ());// Write data read from the stream to lbinfo28}
Catch (Exception ex)
{
MessageBox. Show (ex. Message ); // Capture exceptions
}

(3) Finally, close the socket connection and release the resource. You can directly perform this operation in the formclosed event of the form, as shown below.
S. Shutdown (socketshutdown. Both);
S. Close ();
now, all the servers and clients have been designed. The running effect is shown below.
to run a socket-Based C/S instance, start the server program and click "start server", as shown in figure 17-4. Then start the client, input data in textbox1 (both Chinese and English), and click send multiple times, as shown in Figure 17-5.
the server status is 17-6.
received data from the client
as shown in Figure 17-6, the server has received data from the client, as shown in figure 17-5, the client also receives feedback from the server. In addition, in this example, multiple clients can send and receive data to one server at the same time, and have passed the test on three computers (one server and two clients. This example only implements the simplest data transmission between the server and the client. If you are interested, you can add other functions on this basis. For example, you can use the database knowledge mentioned above, write a user logon authentication on the server side so that the client can send and receive data only after the authentication.
in the network, sockets are often used to send and receive data. This section mainly uses the basic socket knowledge introduced in several sections to complete a simple stream-Based C/S Mode example. In the next section, we will introduce another transmission method-based on datagram (UDP ).

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.