Microsoft KB Archive/821768

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

Article ID: 821768

Article Last Modified on 4/19/2007

-

APPLIES TO


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

-



IN THIS TASK

 * SUMMARY
 * Create a TCP Client Application
 * Create a TCP Server (Listener) Application
 * Test the Sample
 * REFERENCES



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
 Start Microsoft Visual Studio .NET or Microsoft Visual Basic 2005. On the File menu, click New, and then click Project. Under Project types, click Visual Basic Projects.

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

By default, Module1.vb is created.  Replace the code in Module1.vb with the following code: Imports System.Net.Sockets Imports System.Text

Class CTestTCPClient Shared Sub Main

Dim tcpClient As New System.Net.Sockets.TcpClient

'&quot;Localhost&quot; 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(&quot;Localhost&quot;, 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(&quot;Is anybody listening...&quot;) 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((&quot;TCP Server returned: &quot; + returndata)) Else If Not networkStream.CanRead Then Console.WriteLine(&quot;Could not write data to data stream&quot;) tcpClient.Close Else If Not networkStream.CanWrite Then Console.WriteLine(&quot;Could not read data from data stream&quot;) tcpClient.Close End If           End If        End If        ' Pause to let the user view the console output. Console.ReadLine End Sub End 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
 Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.</li> On the File menu, click New, and then click Project.</li> Under Project types, click Visual Basic Projects.

Note In Visual Studio 2005, click Visual Basic under Project Types.</li> Under Templates, click Console Application.</li> Name the project TestTCPServer, and then click OK.

By default, Moudle1.vb is created.</li>  Replace the following code with the code in Module1.vb: Imports System.Net.Sockets Imports System.net Imports System.Text Imports System.Net.DnsPermissionAttribute Imports 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

'&quot;Localhost&quot; 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(&quot;Localhost&quot;).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(&quot;TCP Server is up and waiting for Client connection...&quot;) Try ''Accept the pending client connection and return a TcpClient for communication. Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient Console.WriteLine(&quot;Connection accepted.&quot;) ' 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((&quot;Client sent: &quot; + clientdata)) Dim responseString As String = &quot;Successfully connected to TCP server.&quot; Dim sendBytes As [Byte] = Encoding.ASCII.GetBytes(responseString) networkStream.Write(sendBytes, 0, sendBytes.Length) Console.WriteLine((&quot;Message Sent by TCP Server /> : &quot; + responseString)) 'Close TcpListener and TcpClient. tcpClient.Close tcpListener.Stop Console.WriteLine(&quot;Exit&quot;) Console.ReadLine Catch e As Exception Console.WriteLine(e.ToString) Console.ReadLine End Try End Sub End 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. </li></ol>

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

<div class="references_section">