TCP Client – VB.Net


The following was written with the help of a tutorial. I will explain my understanding of the code in order to help others understand it.

Imports System.Net.Sockets
Imports System.Text
Class TCPCli
    Shared Sub Main()

        Dim tcpClient As New System.Net.Sockets.TcpClient()
        tcpClient.Connect("127.0.0.1", 8000)
        Dim networkStream As NetworkStream = tcpClient.GetStream()
        If networkStream.CanWrite And networkStream.CanRead Then
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there")
            networkStream.Write(sendBytes, 0, sendBytes.Length)
            Dim bytes(tcpClient.ReceiveBufferSize) As Byte
            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
            Dim returndata As String = Encoding.ASCII.GetString(bytes)
            Console.WriteLine(("Host returned: " + returndata))
        Else
            If Not networkStream.CanRead Then
               Console.WriteLine("cannot not read data to this stream")
                tcpClient.Close()
            Else
                If Not networkStream.CanWrite Then
                    Console.WriteLine("cannot write data from this stream")
                    tcpClient.Close()
                End If
            End If
        End If
        Console.ReadLine()
    End Sub
End Class

This project was written in conjunction with my TCP Listener which this client will connect to, send a brief message, recieve a reply and then disconnect.

Now to explaining it.

Imports System.Net.Sockets
Imports System.Text

As before in the TCP Server, We need to import the “System.Net.Sockets” commands to allow the use of the TCP Sockets and the “System.Text” for the use of the encoding of bytes.

Class TCPCli
    Shared Sub Main()

Bogstandard console initialisation code. Make a class called TCPCli for calling later, and then run main subroutine.

       Dim tcpClient As New TcpClient()
        tcpClient.Connect("127.0.0.1", 8000)

Now, using the “System.Net.Sockets” Commands, we will create a TCP Client object, We then tell it to connect to the loopback address of the computer on port 8000.

        Dim networkStream As NetworkStream = tcpClient.GetStream()

Now we tell the console to listen to the connection stream for any data transmitted across it.

        If networkStream.CanWrite And networkStream.CanRead Then
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there")
            networkStream.Write(sendBytes, 0, sendBytes.Length)

The first line is some error checking, If we can read the stream, then we have a connection, as well as if we can write to it. If everything is fine, we move onto the next piece.
We create a byte array and encode the text “Is anybody there” into bytes for transmission across the stream.

We then write to the stream the encoded bytes.

            Dim bytes(tcpClient.ReceiveBufferSize) As Byte
            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
            Dim returndata As String = Encoding.ASCII.GetString(bytes)
            Console.WriteLine(("Host returned: " + returndata))

The first line is for dimming the byte as a buffer with the size of the recieve buffer, We then read any data trasmitted across the stream and store it into the byte buffer.

The data is then encoded on the third line back into ASCII so it would represent number and letters.
We then write to the console the words “Host Returned:” and any text the server was responded with.

        Else
            If Not networkStream.CanRead Then
               Console.WriteLine("cannot not read data to this stream")
                tcpClient.Close()
            Else
                If Not networkStream.CanWrite Then
                    Console.WriteLine("cannot write data from this stream")
                    tcpClient.Close()
                End If
            End If
        End If
        Console.ReadLine()
    End Sub
End Class

The final lines of code are self explanatory, If we cannot read the data stream, then there must be a error and notify the user then shutdown the connection. The same if we cannot write to the stream, notify the user and shut the connection

The final “Console.ReadLine()” is to let the pause the console so the user can view the message

Thanks for reading, hope it helped.

About these ads

About Danny Goodayle

CEO of Rampant Studios
This entry was posted in Development and tagged , , , , , , , . Bookmark the permalink.

8 Responses to TCP Client – VB.Net

  1. nala says:

    thank you for your effort

  2. Faouzi says:

    Thanks man.it was very useful.
    But do you know how we can ping a server ip/port and get the response (text)?Thx in advance :).

    • warrozo says:

      Hey man,

      Sure just change the lines

      Dim tcpClient As New System.Net.Sockets.TcpClient()
      tcpClient.Connect(“127.0.0.1″, 8000)

      to
      Dim tcpClient As New System.Net.Sockets.TcpClient()
      tcpClient.Connect(IPADDRESS, PORT)

      Enjoy :)

  3. linn145 says:

    ehm… anyone know how to use the code ?…. paste inside the form or inside the button?

  4. Md Azmil says:

    Hi warrozo,

    Can this be used to receive email? If so, do you know any link that can help me receive email? I am using Microsoft Visual Studio 2005. I am working in vb.net language.

    • warrozo says:

      Hey Md Azmil,
      Its a basic sockets tutorial however if you search around for tutorials on recieving emails via TCP im sure you’ll find something.
      Sorry i cant be more help!
      Dan.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s