|
VB .NET TcpListener Program Example
Create a new class library project and you might want to use TcpListenertSampleVB as the name.
|
Next, rename the class to tcplistenersample by renaming the source file name to reflect the application that we are going to developed.
Add/edit the following Import directives at the top of the file.
Imports System Imports System.Net Imports System.Net.Sockets |
Next, add the usage() subroutine and its code
' Displays simple usage information. Shared Sub usage() Console.WriteLine("Usage: TcpListenerSampleVB [-l address] [-p port] [-x size]") Console.WriteLine() Console.WriteLine("Available options:") Console.WriteLine(" -l address Local address for TCP server to listen on") Console.WriteLine(" -p port Local port for TCP server to listen on") Console.WriteLine(" -x size Size of send and receive buffers") Console.WriteLine() End Sub |
Then, add the Main() subroutine code.
' <param name="args">Command line arguments</param> Shared Sub Main() Dim listenInterface As IPAddress = IPAddress.Any Dim listenPort As Short = 5150 Dim bufferSize As Integer = 4096 Dim i As Integer
' Parse the command line Dim args As String() = Environment.GetCommandLineArgs()
usage()
For i = 1 To args.GetUpperBound(0) - 1 Try Dim CurArg() As Char = args(i).ToCharArray(0, args(i).Length) If (CurArg(0) = "-") Or (CurArg(0) = "/") Then Select Case Char.ToLower(CurArg(1), System.Globalization.CultureInfo.CurrentCulture) Case "l" ' Local interface server should listen on i = i + 1 listenInterface = IPAddress.Parse(args(i)) Case "p" ' Port number for the destination i = i + 1 listenPort = System.Convert.ToInt16(args(i)) Case "x" ' Size of the send and receive buffers i = i + 1 bufferSize = System.Convert.ToInt32(args(i)) Case Else usage() Exit Sub End Select End If
Catch e As Exception usage() Exit Sub End Try
Next
Dim tcpServer As TcpListener = Nothing Dim tcpClient As tcpClient = Nothing Dim tcpStream As NetworkStream = Nothing Dim sendBuffer(bufferSize) As Byte Dim receiveBuffer(bufferSize) As Byte Dim byteCount() As Byte Dim bytesToRead As Integer = 0 Dim nextReadCount, rc As Integer
' Initialize the send buffer Console.WriteLine("Initializing the send buffer...") For i = 0 To sendBuffer.Length - 1 sendBuffer(i) = CByte(65) Next
Try ' Create the TCP server Console.WriteLine("Creating the TCP server...") tcpServer = New TcpListener(listenInterface, listenPort)
Console.WriteLine("TcpListener created on address {0} and port {1}", _ listenInterface.ToString(), _ listenPort.ToString() _ )
' Start listening for connections Console.WriteLine("Start listening for connections...") tcpServer.Start()
' Wait for a client connection Console.WriteLine("Waiting for a client connection...") tcpClient = tcpServer.AcceptTcpClient()
' Get the NetworkStream so we can do Read and Write on the client connection Console.WriteLine("Getting the NetworkStream for Reading and Writing on the client connection...") tcpStream = tcpClient.GetStream() byteCount = BitConverter.GetBytes(bytesToRead)
' First read the number of bytes the client is sending Console.WriteLine("Reading the number of bytes the client is sending...") tcpStream.Read(byteCount, 0, byteCount.Length) bytesToRead = BitConverter.ToInt32(byteCount, 0)
' Receive the data Console.WriteLine("Receive, Read & display data...") While (bytesToRead > 0) ' Make sure we don't read beyond what the first message indicates ' This is important if the client is sending multiple "messages" -- ' but in this sample it sends only one If (bytesToRead < receiveBuffer.Length) Then nextReadCount = bytesToRead Else nextReadCount = receiveBuffer.Length End If
' Read some data rc = tcpStream.Read(receiveBuffer, 0, nextReadCount)
' Display what we read Dim readText As String = System.Text.Encoding.ASCII.GetString(receiveBuffer, 0, rc) Console.WriteLine("Received: {0}", readText)
bytesToRead -= rc End While
' First send the number of bytes the server is responding with Console.WriteLine("Sending the number of bytes the server is responding with...") byteCount = BitConverter.GetBytes(sendBuffer.Length)
tcpStream.Write(byteCount, 0, byteCount.Length)
' Send the actual data Console.WriteLine("Send the actual data...") tcpStream.Write(sendBuffer, 0, sendBuffer.Length)
' Close up the client Console.WriteLine("Closing up the client...") tcpStream.Close() tcpStream = Nothing
tcpClient.Close() tcpClient = Nothing
Catch err As SocketException ' Exceptions on the TcpListener are caught here Console.WriteLine("Socket error occurred: {0}", err.Message)
Catch err As System.IO.IOException ' Exceptions on the NetworkStream are caught here Console.WriteLine("I/O error: {0}", err.Message)
Finally ' Close any remaining open resources Console.WriteLine("Closing any remaining open resources...") If (Not IsNothing(tcpServer)) Then tcpServer.Stop() End If If (Not IsNothing(tcpStream)) Then tcpStream.Close() End If If (Not IsNothing(tcpClient)) Then tcpClient.Close() End If End Try End Sub |
Next, we need to change the DLL to EXE type program so that we can run it n console mode. Select the project folder > Right click mouse > Select Properties context menu.
In order to test his project, change the Application type: to Console Application and the Startup object: to Sub Main.
Next, build the project and make sure there is no error that can be seen in the Output window if any.
Then, run the project. Any error will be thrown by the exception handlers.
If the following Windows Security Alert box displayed, click the Unblock button.
The following is the sample output that uses the default values.
Testing the tcp listener with the tcp client. In this case we use the TcpClientSampleVB program as a client. Firstly, we run the listener.
Next, run the client tcp.
![]() |
|
The following is the tcp listener screenshot after the communication was completed.
You may want to test this program on real network with the listener and the client run on different hosts and try using the available options.
Create a new CLR console application project and you might want to use TcpClientSampleCP as the name.
Add the following code.
// TcpClientSampleCP.cpp : main project file.
#include "stdafx.h"
using namespace System; using namespace System::Net; using namespace System::Net::Sockets;
/// <summary> /// Displays simple usage information. /// </summary> static void usage() { Console::WriteLine("Usage: TcpClientSample.exe [-n server] [-p port] [-x size]"); Console::WriteLine("Available options:"); Console::WriteLine(" -n server Name or address of server to connect to"); Console::WriteLine(" -p port Port number to connect to server on"); Console::WriteLine(" -x size Size of send and receive buffers"); Console::WriteLine(); }
int main(array<System::String ^> ^args) { // Initial/default values String^ serverAddress = "localhost"; unsigned short serverPort = 5150; int bufferSize = 1024;
// Parse the command line if(args->Length != 0) { for (int i = 0; i < args->Length; i++) { try { if ((args[i][0] == '-') || (args[i][0] == '/')) { switch (Char::ToLower(args[i][1])) { case 'n': // String name or address of server to connect to serverAddress = args[++i]; break; case 'p': // Port number for the destination serverPort = Convert::ToUInt16(args[++i]); break; case 'x': // Size of the send and receive buffers bufferSize = Convert::ToInt32(args[++i]); break; default: usage(); return 0; } } } catch(Exception^ err) { Console::WriteLine("TCP client: Error - {0}", err->Message); usage(); return 0; } } } else { usage(); return 0; }
TcpClient^ simpleTcp = nullptr; NetworkStream^ tcpStream = nullptr; array<Byte>^ sendBuffer = gcnew array<Byte>(bufferSize); array<Byte>^ receiveBuffer = gcnew array<Byte>(bufferSize); array<Byte>^ byteCount; int bytesToRead = 0, nextReadCount, rc;
// Initialize the send buffer Console::WriteLine("TCP client: Initializing the send buffer..."); for (int i = 0; i < sendBuffer->Length; i++) sendBuffer[i] = (Byte)'X';
try { // Create the client and indicate the server to connect to Console::WriteLine("TCP client: Creating the client and indicate the server to connect to..."); simpleTcp = gcnew TcpClient(serverAddress, (int)serverPort);
// Retrieve the NetworkStream so we can do Read and Write Console::WriteLine("TCP client: Retrieving the NetworkStream so we can do Read and Write..."); tcpStream = simpleTcp->GetStream();
// First send the number of bytes the client is sending Console::WriteLine("TCP client: Sending the number of bytes the client is sending..."); byteCount = BitConverter::GetBytes(sendBuffer->Length); tcpStream->Write(byteCount, 0, byteCount->Length);
// Send the actual data Console::WriteLine("TCP client: Sending the actual data..."); tcpStream->Write(sendBuffer, 0, sendBuffer->Length); tcpStream->Read(byteCount, 0, byteCount->Length);
// Read how many bytes the server is responding with Console::WriteLine("TCP client: Reading how many bytes the server is responding with..."); bytesToRead = BitConverter::ToInt32(byteCount, 0);
// Receive the data Console::WriteLine("TCP client: Receiving, reading & displaying the data..."); while (bytesToRead > 0) { // Make sure we don't read beyond what the first message indicates // This is important if the client is sending multiple "messages" -- // but in this sample it sends only one if (bytesToRead < receiveBuffer->Length) nextReadCount = bytesToRead; else nextReadCount = receiveBuffer->Length;
// Read the data rc = tcpStream->Read(receiveBuffer, 0, nextReadCount);
// Display what was read String^ readText = Text::Encoding::ASCII->GetString(receiveBuffer, 0, rc); Console::WriteLine("TCP client: Received: {0}", readText); bytesToRead -= rc; } } catch (SocketException^ err) { // Exceptions on the TcpListener are caught here Console::WriteLine("Socket error\n - {0}", err->Message); } catch (IO::IOException^ err) { // Exceptions on the NetworkStream are caught here Console::WriteLine("TCP client: I/O error: {0}", err->Message); } finally { // Close any remaining open resources Console::WriteLine("TCP client: Closing all the opening resources..."); if (tcpStream != nullptr) tcpStream->Close(); if (simpleTcp != nullptr) simpleTcp->Close(); } return 0; } |
Next, build the project and make sure there is no error. Then, run the project. Any error will be thrown by the exception handlers. The following is the sample output.
The following are sample outputs when run at the command prompt for tcp listener and tcp client. The listener program used is the previously created, TcpListenerSampleCP.exe. Firstly, we run the listener. The listener is waiting a connection from client.
Then we run the tcp client.
The following is the tcp listener output screenshot when the communication was completed.
You may want to test this program on real network with the listener and the client run on different hosts and try using different available options.