< Controlling A Thread & Program Examples | Main | VB .NET WinForm Program Example >

 


 

Chapter 3 Part 3:

Threading and the Asynchronous Pattern

 

 

What do we have in this chapter 3 Part 3?

  1. C# WinForm Program Example

 

 

C# WinForm Program Example

 

Create a new Windows Form Application project.

 

C# WinForm Program Example - a new Windows Form project creation

 

Drag, drop and rearrange the related controls from the Toolbox window and customize the properties.

 

C# WinForm Program Example - using controls from the Toolbox

 

Customize the form using the following information.

 

Control

Property

Value

Form1

Text

WinNetworkIOCS

Button

Text

Connect, Send, Close

 

Name

ConnectButton

Label1

Text

IP Address:

TextBox1

Name

IPAddressBox

 

Text

127.0.0.1

Label2

Text

Port:

TextBox2

Name

PortBox

 

Text

5150

Label3

Text

Message to send:

TextBox3

Name

SendMessageBox

 

Text

This is a test message…

 

Multiline

True

 

C# WinForm Program Example - arranging the controls in the Windows Form

 

To invoke the Properties page (if any), select object > Right click mouse > Select Properties context menu. If the Properties page already docked in the VS IDE, then selecting the object will bring the Properties page for the object automatically.

 

C# WinForm Program Example - invoking the property page of the controls in Windows Form

 

The following is the Properties page for Form1 example.

 

C# WinForm Program Example - The Properties page for the Windows Form controls

 

The following Figure shows the almost complete Windows form.

 

C# WinForm Program Example - an almost complete WinForm design

 

Next, drag and drop a StatusStrip container component at the bottom of the Windows form.

 

C# WinForm Program Example - adding StatusStrip control

 

Then, add a StatusLabel for the StatusStrip.

 

C# WinForm Program Example - setting the StatusLabel to the StatusStrip

 

Do some customization for the StatusLabel. Select the statusStrip1 > right click mouse > select Edit Items context menu.

 

C# WinForm Program Example - editing the StatusStrip control

 

Select the StatusLabel1 in the left window (Members:). Change the Text to None and Name to StatusBar. Click OK.

 

C# WinForm Program Example - customizing the StatusLabel properties

 

The following is a completed Windows form design for this project. Now, we are ready to add codes.

 

C# WinForm Program Example - a completed WinForm design

 

Adding codes for the actions. First of all, double click the top button. This will bring the code page with a button click template. Add the following two lines code to the ConnectButton_Click().

 

private void ConnectButton_Click(object sender, EventArgs e)

{

    DisableFields();

    DoNetworkingConnection();

}

 

C# WinForm Program Example - adding code for button click event

 

Don’t forget to add the following using directives.

 

using System.Net;

using System.Net.Sockets;

using System.Threading;

using System.IO;

 

C# WinForm Program Example - adding using directives

 

Continue adding more codes just after the ConnectButton_Click() closing bracket.

 

private void DisableFields()

{

         PortBox.Enabled = false;

         IPAddressBox.Enabled = false;

         SendMessageBox.Enabled = false;

         ConnectButton.Enabled = false;

}

 

private void EnableFields()

{

          PortBox.Enabled = true;

          IPAddressBox.Enabled = true;

          SendMessageBox.Enabled = true;

          ConnectButton.Enabled = true;

}

 

C# WinForm Program Example - adding DisableField() and EnableField() methods

 

Add the following code to write messages to the status bar of the Windows form.

 

private void WriteToStatusBar(string Message)

{

            EnableFields();

            StatusBar.Text = Message;

}

 

C# WinForm Program Example - adding WriteToStatusBar() method

 

Then, add code for the networking.

 

        private void DoNetworkingConnection()

        {

            Thread MyThread = null;

 

            try

            {

                ThreadStart ThreadMethod = new ThreadStart(ConnectTo);

 

                MyThread = new Thread(ThreadMethod);

            }

            catch (Exception e)

            {

                WriteToStatusBar("Failed to create thread with error: " + e.Message);

                return;

            }

 

            try

            {

                MyThread.Start();

            }

            catch (Exception e)

            {

                WriteToStatusBar("The thread failed to start with error: " + e.Message);

            }

        }

 

C# WinForm Program Example - adding DoNetworkingConnection() method

 

Finally, add the following code for the real connection.

 

        private void ConnectTo()

        {

            string ServerName = this.IPAddressBox.Text;

            int Port = System.Convert.ToInt32(this.PortBox.Text);

 

            WriteToStatusBar("IP Address: " + ServerName + "Port: " + Port);

            Socket ClientSocket = null;

 

            try

            {

                // Let's connect to a listening server

                try

                {

                    ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

                    WriteToStatusBar("Socket is OK...");

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to create client Socket: " + e.Message);

                }

 

                IPEndPoint ServerEndPoint = new IPEndPoint(IPAddress.Parse(ServerName), Convert.ToInt16(Port));

 

                try

                {

                    ClientSocket.Connect(ServerEndPoint);

                    WriteToStatusBar("Connect() is OK...");

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to connect client Socket: " + e.Message);

                }

            }

            catch (Exception e)

            {

                WriteToStatusBar(e.Message);

                ClientSocket.Close();

                return;

            }

 

            // Let's create a network stream to communicate over the connected Socket.

            NetworkStream ClientNetworkStream = null;

 

            try

            {

                try

                {

                    // Setup a network stream on the client Socket

                    ClientNetworkStream = new NetworkStream(ClientSocket, true);

                    WriteToStatusBar("Instantiating NetworkStream...");

                }

                catch (Exception e)

                {

                    // We have to close the client socket here because the network

                    // stream did not take ownership of the socket.

                    ClientSocket.Close();

                    throw new Exception("Failed to create a NetworkStream with error: " + e.Message);

                }

 

                StreamWriter ClientNetworkStreamWriter = null;

 

                try

                {

                    // Setup a Stream Writer

                    ClientNetworkStreamWriter = new StreamWriter(ClientNetworkStream);

                    WriteToStatusBar("Setting up StreamWriter...");

                }

                catch (Exception e)

                {

                    ClientNetworkStream.Close();

                    throw new Exception("Failed to create a StreamWriter with error: " + e.Message);

                }

 

                try

                {

                    ClientNetworkStreamWriter.Write(this.SendMessageBox.Text.ToString());

                    ClientNetworkStreamWriter.Flush();

                    WriteToStatusBar("We wrote " + this.SendMessageBox.Text.Length.ToString() + " character(s) to the server.");

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to write to client NetworkStream with error: " + e.Message);

                }

            }

            catch (Exception e)

            {

                WriteToStatusBar(e.Message);

            }

            finally

            {

                // Close the network stream once everything is done

                ClientNetworkStream.Close();

            }

        }

 

Build and run the project. The following is a sample output and it is a client/sender program. In order to see the real activities, we will test this client together with the previously created stream server/receiver program (NetworkStreamSampleCSReceiver.exe). In this case we test both programs on the same local host and you may want to test it on different hosts which mean run the receiver on host A and run the sender on host B and change the IP address of the sender accordingly.

 

C# WinForm Program Example - Winform output in action  

 

Running both, the receiver and the sender programs. Firstly run the previous receiver program (NetworkStreamSampleCSReceiver.exe). The receiver is waiting a connection from sender.

 

C# WinForm Program Example - running the receiver/server program and ready for connection

 

Then, run the sender/client program (WinForm application). The following is a sample output for both the sender and the receiver.

 

C# WinForm Program Example - running the WinForm program by sending some messages. The sent byte can be seen in the receiver screen

 

Take note that the numbers output in the receiver program represent the ASCII code for the characters sent, for example the first alphabet 'I' is equivalent to '73' ASCII. A complete source codes for this part is given below.

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Net;

using System.Net.Sockets;

using System.Threading;

using System.IO;

 

namespace WinNetworkIOCS

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void ConnectButton_Click(object sender, EventArgs e)

        {

            DisableFields();

            DoNetworkingConnection();

        }

 

        private void DisableFields()

        {

            PortBox.Enabled = false;

            IPAddressBox.Enabled = false;

            SendMessageBox.Enabled = false;

            ConnectButton.Enabled = false;

        }

 

        private void EnableFields()

        {

            PortBox.Enabled = true;

            IPAddressBox.Enabled = true;

            SendMessageBox.Enabled = true;

            ConnectButton.Enabled = true;

        }

 

        private void WriteToStatusBar(string Message)

        {

            EnableFields();

            StatusBar.Text = Message;

       }

 

        private void DoNetworkingConnection()

        {

            Thread MyThread = null;

 

            try

            {

                ThreadStart ThreadMethod = new ThreadStart(ConnectTo);

 

                MyThread = new Thread(ThreadMethod);

            }

            catch (Exception e)

            {

                WriteToStatusBar("Failed to create thread with error: " + e.Message);

                return;

            }

 

            try

            {

                MyThread.Start();

            }

            catch (Exception e)

            {

                WriteToStatusBar("The thread failed to start with error: " + e.Message);

            }

        }

 

        private void ConnectTo()

        {

            string ServerName = this.IPAddressBox.Text;

            int Port = System.Convert.ToInt32(this.PortBox.Text);

 

            WriteToStatusBar("IP Address: " + ServerName + "Port: " + Port);

            Socket ClientSocket = null;

 

            try

            {

                // Let's connect to a listening server

                try

                {

                    ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

                    WriteToStatusBar("Socket is OK...");

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to create client Socket: " + e.Message);

                }

 

                IPEndPoint ServerEndPoint = new IPEndPoint(IPAddress.Parse(ServerName), Convert.ToInt16(Port));

 

                try

                {

                    ClientSocket.Connect(ServerEndPoint);

                    WriteToStatusBar("Connect() is OK...");

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to connect client Socket: " + e.Message);

                }

            }

            catch (Exception e)

            {

                WriteToStatusBar(e.Message);

                ClientSocket.Close();

                return;

            }

 

            // Let's create a network stream to communicate over the connected Socket.

            NetworkStream ClientNetworkStream = null;

 

            try

            {

                try

                {

                    // Setup a network stream on the client Socket

                    ClientNetworkStream = new NetworkStream(ClientSocket, true);

                    WriteToStatusBar("Instantiating NetworkStream...");

                }

                catch (Exception e)

                {

                    // We have to close the client socket here because the network

                    // stream did not take ownership of the socket.

                    ClientSocket.Close();

                    throw new Exception("Failed to create a NetworkStream with error: " + e.Message);

                }

 

                StreamWriter ClientNetworkStreamWriter = null;

 

                try

                {

                    // Setup a Stream Writer

                    ClientNetworkStreamWriter = new StreamWriter(ClientNetworkStream);

                    WriteToStatusBar("Setting up StreamWriter...");

                }

                catch (Exception e)

                {

                    ClientNetworkStream.Close();

                    throw new Exception("Failed to create a StreamWriter with error: " + e.Message);

                }

 

                try

                {

                    ClientNetworkStreamWriter.Write(this.SendMessageBox.Text.ToString());

                    ClientNetworkStreamWriter.Flush();

                    WriteToStatusBar("We wrote " + this.SendMessageBox.Text.Length.ToString() + " character(s) to the server.");

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to write to client NetworkStream with error: " + e.Message);

                }

            }

            catch (Exception e)

            {

                WriteToStatusBar(e.Message);

            }

            finally

            {

                // Close the network stream once everything is done

                ClientNetworkStream.Close();

            }

        }

    }

}

 

 

 


 

< Controlling A Thread & Program Examples | Main | VB .NET WinForm Program Example >