You are currently offline, waiting for your internet to reconnect

How to program the Microsoft Windows Sockets interface and the network connections in Visual Basic .NET or in Visual Basic 2005

SUMMARY
This step-by-step article describes how to program the Microsoft Windows Sockets (Winsock) interface and the network connections in Microsoft Visual Basic .NET or in Microsoft Visual Basic 2005. In the sample, a simple Transfer Control Protocol (TCP) client application that is named TestTCPClient and a simple TCP Server (listener) application that is named TestTCPServer use the Windows Sockets interface to communicate with each other.

back to the top

Create a TCP Client Application


  1. Start Microsoft Visual Studio .NET or Microsoft Visual Basic 2005.
  2. On the File menu, click New, and then click Project.
  3. Under Project types, click Visual Basic Projects.

    Note In Visual Studio 2005, click Visual Basic under Project Types.
  4. Under Templates, click Console Application.
  5. Name the project TestTCPClient, and then click OK.

    By default, Module1.vb is created.
  6. Replace the code in Module1.vb with the following code:
    Imports System.Net.SocketsImports System.TextClass CTestTCPClient    Shared Sub Main()        Dim tcpClient As New System.Net.Sockets.TcpClient        '"Localhost" string is used when the client and the listener are on the same computer.        'If the listener is listening at a computer that is different from the client, provide the host name of the computer        'where the listener is listening.        tcpClient.Connect("Localhost", 8000)        Dim networkStream As NetworkStream = tcpClient.GetStream()        If networkStream.CanWrite And networkStream.CanRead Then            ' Do a simple write.            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody listening...")            networkStream.Write(sendBytes, 0, sendBytes.Length)            ' Read the NetworkStream into a byte buffer.            Dim bytes(tcpClient.ReceiveBufferSize) As Byte            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))            ' Output the data received from the host to the console.            Dim returndata As String = Encoding.ASCII.GetString(bytes)            Console.WriteLine(("TCP Server returned: " + returndata))        Else            If Not networkStream.CanRead Then                Console.WriteLine("Could not write data to data stream")                tcpClient.Close()            Else                If Not networkStream.CanWrite Then                    Console.WriteLine("Could not read data from data stream")                    tcpClient.Close()                End If            End If        End If        ' Pause to let the user view the console output.        Console.ReadLine()    End SubEnd Class 
    This code creates a new instance of the tcpClient class, calls the Connect method, and then gains access to the underlying data stream by using the GetStream() method of the NetworkStream class. The message is converted to a byte array, sent to the data stream, and then read the data stream for the response from the TCP Server (listener) application.
back to the top

Create a TCP Server (Listener) Application

  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, click New, and then click Project.
  3. Under Project types, click Visual Basic Projects.

    Note In Visual Studio 2005, click Visual Basic under Project Types.
  4. Under Templates, click Console Application.
  5. Name the project TestTCPServer, and then click OK.

    By default, Moudle1.vb is created.
  6. Replace the following code with the code in Module1.vb:
    Imports System.Net.SocketsImports System.netImports System.TextImports System.Net.DnsPermissionAttributeImports System.Security.Permissions'DnsPermissionAttribute specifies permission to request information from Domain Name Servers.<DnsPermissionAttribute(SecurityAction.Demand, Unrestricted:=True)> Class CTestTCPServer    Shared Sub Main()        'Listening must be on the same port that the client is connected on.         Const portNumber As Integer = 8000        '"Localhost" string is used when the client and the listener are on the same computer.        'If the listener is listening at a computer that is different from the client, then provide the host name of the computer        'where the listener is listening.        Dim tcpListener As New TcpListener(CType(Dns.Resolve("Localhost").AddressList(0), IPAddress), portNumber)        'Comment the previous line and uncomment the following line if you are using Visual Basic .NET (2003).        'Dim tcpListener As New TcpListener(portNumber)        tcpListener.Start()        Console.WriteLine("TCP Server is up and waiting for Client connection...")        Try            ''Accept the pending client connection and return a TcpClient for communication.             Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()            Console.WriteLine("Connection accepted.")            ' Get the data stream.            Dim networkStream As NetworkStream = tcpClient.GetStream()            ' Read the data stream into a byte array.            Dim bytes(tcpClient.ReceiveBufferSize) As Byte            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))            ' Return the data received from the client to the console.            Dim clientdata As String = Encoding.ASCII.GetString(bytes)            Console.WriteLine(("Client sent: " + clientdata))            Dim responseString As String = "Successfully connected to TCP server."            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)            networkStream.Write(sendBytes, 0, sendBytes.Length)            Console.WriteLine(("Message Sent by TCP Server /> : " + responseString))            'Close TcpListener and TcpClient.            tcpClient.Close()            tcpListener.Stop()            Console.WriteLine("Exit")            Console.ReadLine()        Catch e As Exception            Console.WriteLine(e.ToString())            Console.ReadLine()        End Try    End SubEnd Class
    The TestTCPServer application creates a new instance of the tcpListener class on the port, calls the Start() method, and then accepts the pending client request by using the AcceptTcpClient() method. The AcceptTcpClient() method returns the tcpClient object that you can use to send and to receive data.
back to the top

Test the Sample

To test the sample, build and run the TestTCPServer application, and then build and run the TestTCPClient application. The messages in the console window indicate that the TestTCPClient application and the TestTCPServer application are communicating by using the Windows Sockets interface.
back to the top
REFERENCES
For more information about the Sockets class, visit the following Microsoft Developer Network (MSDN) Web site:back to the top
Properties

Article ID: 821768 - Last Review: 04/19/2007 07:34:18 - Revision: 2.5

Microsoft Visual Basic 2005, Microsoft Visual Basic .NET 2003 Standard Edition, Microsoft Visual Basic .NET 2002 Standard Edition

  • kbvs2005applies kbvs2005swept kbwinsock kbdev kbconsole kbhowtomaster KB821768
Feedback
ms.dqp0';m.content='true';document.getElementsByTagName('head')[0].appendChild(m);" onload="var m=document.createElement('meta');m.name='ms.dqp0';m.content='false';document.getElementsByTagName('head')[0].appendChild(m);" src="http://c1.microsoft.com/c.gif?">