A complete example of C # socket-based CS mode

Source: Internet
Author: User

Based on the socket server-side implementation of this example is to establish a multi-client and server data transfer, the first design server. Open VS2008 and create 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 Adding a list of controls

Control

Name

Text

ListBox

Lbinfo

Label

Label

Button

Button1

Start the server

A well-designed interface is shown in 17-2.


Next began to use the knowledge of the previous design server, mainly divided into the following steps.
(1) The first is the inclusion of a number of 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;                                    Defining a Socket Object
private Thread th; The client connects to the server's thread
Public Socket CSocket; Socket object for a single client connection
Public NetworkStream NS; Network flow
Public StreamReader SR; Stream read
Public StreamWriter SW; Stream Write
Private delegate void Settextcallback (); For operation of Main Line program control parts


(2) Next is to design the management of client connection, mainly including the connection between the server and the client and send and receive data problems, 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); Establish network flow for easy reading of data
sr = new StreamReader (NS); Instantiate stream Read Object
SW = new StreamWriter (NS); Instantiating a write Stream object
Test (); Reading from the stream
Sw. WriteLine ("Receive request, allow connection"); Writing data to the stream
Sw. Flush (); Cleanup buffer
}
Else
{
MessageBox.Show ("Connection failed");
}
}
catch (SocketException ex)
{
MessageBox.Show (ex. Message); Capturing socket exceptions
}
catch (Exception es)
{
MessageBox.Show ("Other exceptions" + es.) Message); Catching other exceptions
}
}
}
The use of the following code is mentioned in the 16th chapter about threading usage, which is mainly used to manipulate the controls in the main thread from the current threads, where there is no redundancy//
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, the next step is to use the thread to start, double-click the "Start Server" button and add the following code.

Button1. Enabled = false;
s = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);//Create Socket Object
IPAddress ServerIP = Ipaddress.parse ("222.18.142.171");
IPEndPoint Server = new IPEndPoint (serverip,13); Instantiate the IP and port of the server
S.bind (server);
S.listen (10);
Try
{
th = new Thread (new ThreadStart (communication)); Creating Threads
Th. Start (); Start thread
Label1. Text = "Server started successfully!" ";
}
catch (Exception ex)
{
MessageBox.Show ("Server failed to start! "+ Ex. Message);
}


(4) Finally, when you close the server window, you should also close the thread and the current socket connection, as shown in the code below.

protected override void Dispose (bool disposing)
{
Try
{
if (disposing && (components = null))
{
Components. Dispose ();
Th. Abort ();
Disable data transmission in the current socket connection
S.shutdown (System.Net.Sockets.SocketShutdown.Both);
S.close ();
}
Base. Dispose (disposing);
}
Catch
{
Return
}
}
Next, add the following code for the FormClosed event of the current form.
This. Close ();


At this point, the server is finished design, the following look at the client.
Open VS2008 based on the socket client implementation, and build 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 Adding a list of controls

Control Name

Name

Text

GroupBox

GroupBox1

Send a message 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 mainly divided into the following steps.
(1) The first thing to do is to refer to some namespaces, as shown below.


Using System.Net.Sockets;
Using System.Net;

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

Private Socket S;                                         Defining a Socket Object                  
Public NetworkStream NS; Network flow
Public StreamReader SR;
Public StreamWriter SW; Stream Write

(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
Try
{
S.connect (ServerIP,); Connection server, port number 13
}
catch (Exception ex)
{
MessageBox.Show (ex. Message);
}

{
NS = new NetworkStream (s); Instantiate a network stream
sr = new StreamReader (NS); Instantiate stream Read Object
SW = new StreamWriter (NS); Instantiating a write Stream object
Sw. WriteLine (TextBox1.Text); Writes TextBox1.Text data to a stream
Sw. Flush (); Cleanup buffer
LbInfo.Items.Add (Sr. ReadLine ()); Writes data read from the stream to lbInfo28 }
catch (Exception ex)
{
MessageBox.Show (ex. Message); Catching exceptions
}



(3) Finally, close the socket connection and release the resource, which can be done directly in the FormClosed event of the form, as shown below.
S.shutdown (Socketshutdown.both);
S.close ();
At this point, the server and the client have all been designed, the following see the effect of operation.
The operation of C/s instance based on socket first, start the server program, click the "Start Server" button, shown in 17-4. Then start the client and enter the data in TextBox1 (both English and Chinese), click the "Send" button more than 17-5, as shown.
At this point, the server's status 17-6 is shown.
Receive data sent by the client
As can be seen from Figure 17-6, the server has received data from the client, and figure 17-5 shows that the client also received a feedback message from the server. In addition, this example enables multiple clients to send and receive data to one server at the same time, and has been tested on three computers (one server and two clients). This example just realizes the server and the client the simplest data transmission, if the reader is interested can add other functions on this basis, for example, can take advantage of the knowledge of the previous database, write a user login authentication on the server side, so that the client can send and receive data after verification.
In the network, the socket is often used to send and receive data. This section uses the socket basics described in a few sections to complete a simple flow-based C/S model example. In the next section, you'll see another way to transport-based on datagram (UDP).

A complete example of C # socket-based CS mode

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.