|
VB .NET WinForm Program Example
Create a new Windows Forms Application project. You can use the project and solution name as shown in the following snapshot.
Drag, drop and rearrange the Windows controls as shown in the following Figure. Use the information in the following Table for the controls properties. |
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 |
Drag and drop the StatusStrip control at the bottom of the Form. Then, add a StatusLabel for the StatusStrip.
Next, select the StatusStrip component > Right click mouse > Select Edit Items context menu to customize the StatusLabel.
Select the StatusLabel in the Members: pane. Change the Text value to None and the Name value to StatusBar. Close the Items Collection Editor.
The following is our final Windows form design.
Double click the top button and add the following Imports directives and codes that follow.
Imports System.Net Imports System.Net.Sockets Imports System.Threading Imports System.IO |
Private Sub ConnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectButton.Click DisableFields() DoNetworkingConnection() End Sub |
![]() |
|
Add more codes, DisableFields() and EnableFields() sub routines.
Private Sub DisableFields() PortBox.Enabled = False IPAddressBox.Enabled = False SendMessageBox.Enabled = False ConnectButton.Enabled = False End Sub
Private Sub EnableFields() PortBox.Enabled = True IPAddressBox.Enabled = True SendMessageBox.Enabled = True ConnectButton.Enabled = True End Sub |
Add codes for writing messages to the status bar.
Public Delegate Sub StatusBarWriterDelegateMethod(ByVal Message As String)
Private Sub WriteToStatusBar(ByVal Message As String) Dim SB As StatusBarWriterDelegateMethod = New StatusBarWriterDelegateMethod(AddressOf StatusBarWriter) SB.Invoke(Message) End Sub
Public Sub StatusBarWriter(ByVal MessageToWrite As String) EnableFields() Me.StatusBar.Text = MessageToWrite End Sub |
Next, add codes for the networking part.
Private Sub DoNetworkingConnection() Dim MyThread As Thread = Nothing
Try Dim ThreadMethod As ThreadStart = New ThreadStart(AddressOf ConnectTo)
MyThread = New Thread(ThreadMethod)
Catch e As Exception WriteToStatusBar("Failed to create thread with error: " + e.Message) Exit Sub End Try
Try MyThread.Start() Catch e As Exception WriteToStatusBar("The thread failed to start with error: " + e.Message) End Try End Sub |
Then add codes for connection part.
Private Sub ConnectTo() Dim ServerName As String = Me.IPAddressBox.Text Dim Port As Integer = System.Convert.ToInt32(Me.PortBox.Text)
Dim ClientSocket As Socket = Nothing
Try ' Let's connect to a listening server Try ClientSocket = New Socket(AddressFamily.InterNetwork, _ SocketType.Stream, ProtocolType.IP)
Catch e As Exception Throw New Exception("Failed to create client Socket: " + e.Message) End Try
Dim ServerEndPoint As IPEndPoint = New IPEndPoint( _ IPAddress.Parse(ServerName), Convert.ToInt16(Port))
Try ClientSocket.Connect(ServerEndPoint)
Catch e As Exception Throw New Exception("Failed to connect client Socket: " + e.Message) End Try
Catch e As Exception WriteToStatusBar(e.Message)
ClientSocket.Close() Exit Sub End Try
' Let's create a network stream to communicate over the connected Socket. Dim ClientNetworkStream As NetworkStream = Nothing
Try Try ' Setup a network stream on the client Socket ClientNetworkStream = New NetworkStream(ClientSocket, True)
Catch e As Exception ' 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) End Try
Dim ClientNetworkStreamWriter As StreamWriter = Nothing
Try ' Setup a Stream Writer ClientNetworkStreamWriter = New StreamWriter(ClientNetworkStream)
Catch e As Exception ClientNetworkStream.Close() Throw New Exception("Failed to create a StreamWriter with error: " _ + e.Message) End Try
Try ClientNetworkStreamWriter.Write(Me.SendMessageBox.Text.ToString())
ClientNetworkStreamWriter.Flush()
WriteToStatusBar("We wrote " + Me.SendMessageBox.Text.Length.ToString() _ + " character(s) to the server.")
Catch e As Exception Throw New Exception("Failed to write to client NetworkStream with error: " _ + e.Message) End Try
Catch e As Exception WriteToStatusBar(e.Message)
Finally ' Close the network stream once everything is done ClientNetworkStream.Close() End Try End Sub |
Finally, add code for the form loading.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub |
Build and run the project.
The following snapshot is a sample output. The receiver is waiting for a connection.
In order to see the real activities, we will test this client together with the previously created stream server/receiver program (NetworkStreamSampleCSReceiver.exe or NetworkStreamSampleVBReceiver.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.
Running both, the receiver and the sender programs. Firstly run the previous receiver program (NetworkStreamSampleCSReceiver.exe). The receiver is waiting a connection from sender.
Then, run the sender/client program (WinForm application). The following is a sample output for both the sender and the receiver.
A complete code for this part is given below.
Imports System.Net Imports System.Net.Sockets Imports System.Threading Imports System.IO
Public Class Form1
Private Sub ConnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectButton.Click DisableFields() DoNetworkingConnection() End Sub Private Sub DisableFields() PortBox.Enabled = False IPAddressBox.Enabled = False SendMessageBox.Enabled = False ConnectButton.Enabled = False End Sub
Private Sub EnableFields() PortBox.Enabled = True IPAddressBox.Enabled = True SendMessageBox.Enabled = True ConnectButton.Enabled = True End Sub Public Delegate Sub StatusBarWriterDelegateMethod(ByVal Message As String)
Private Sub WriteToStatusBar(ByVal Message As String) Dim SB As StatusBarWriterDelegateMethod = New StatusBarWriterDelegateMethod(AddressOf StatusBarWriter) SB.Invoke(Message) End Sub
Public Sub StatusBarWriter(ByVal MessageToWrite As String) EnableFields() Me.StatusBar.Text = MessageToWrite End Sub
Private Sub DoNetworkingConnection() Dim MyThread As Thread = Nothing
Try Dim ThreadMethod As ThreadStart = New ThreadStart(AddressOf ConnectTo)
MyThread = New Thread(ThreadMethod)
Catch e As Exception WriteToStatusBar("Failed to create thread with error: " + e.Message) Exit Sub End Try
Try MyThread.Start()
Catch e As Exception WriteToStatusBar("The thread failed to start with error: " + e.Message) End Try End Sub
Private Sub ConnectTo() Dim ServerName As String = Me.IPAddressBox.Text Dim Port As Integer = System.Convert.ToInt32(Me.PortBox.Text)
Dim ClientSocket As Socket = Nothing
Try ' Let's connect to a listening server Try ClientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)
Catch e As Exception Throw New Exception("Failed to create client Socket: " + e.Message) End Try
Dim ServerEndPoint As IPEndPoint = New IPEndPoint( _ IPAddress.Parse(ServerName), Convert.ToInt16(Port))
Try ClientSocket.Connect(ServerEndPoint)
Catch e As Exception Throw New Exception("Failed to connect client Socket: " + e.Message) End Try
Catch e As Exception WriteToStatusBar(e.Message)
ClientSocket.Close() Exit Sub End Try
' Let's create a network stream to communicate over the connected Socket. Dim ClientNetworkStream As NetworkStream = Nothing
Try Try ' Setup a network stream on the client Socket ClientNetworkStream = New NetworkStream(ClientSocket, True)
Catch e As Exception ' 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) End Try
Dim ClientNetworkStreamWriter As StreamWriter = Nothing
Try ' Setup a Stream Writer ClientNetworkStreamWriter = New StreamWriter(ClientNetworkStream)
Catch e As Exception ClientNetworkStream.Close() Throw New Exception("Failed to create a StreamWriter with error: " + e.Message) End Try
Try ClientNetworkStreamWriter.Write(Me.SendMessageBox.Text.ToString())
ClientNetworkStreamWriter.Flush()
WriteToStatusBar("We wrote " + Me.SendMessageBox.Text.Length.ToString() + " character(s) to the server.")
Catch e As Exception Throw New Exception("Failed to write to client NetworkStream with error: " + e.Message) End Try
Catch e As Exception WriteToStatusBar(e.Message)
Finally ' Close the network stream once everything is done ClientNetworkStream.Close() End Try End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub End Class |