How to program the Microsoft Windows Sockets interface and the network connections in Visual Basic .NET or in Visual Basic 2005 (821768)
The information in this article applies to:
- Microsoft Visual Basic 2005
- Microsoft Visual Basic .NET (2003)
- Microsoft Visual Basic .NET (2002)
SUMMARYThis 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 topCreate 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
'"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 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.
- 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 TestTCPServer, and
then click OK.
By default, Moudle1.vb is
created. - 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
'"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 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. back to the topTest the SampleTo 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 topREFERENCESFor more information about the Sockets class, visit the following Microsoft Developer Network (MSDN) Web
site: back to the
top
Modification Type: | Minor | Last Reviewed: | 10/3/2006 |
---|
Keywords: | kbvs2005applies kbvs2005swept kbWinsock kbDev kbConsole kbHOWTOmaster KB821768 kbAudDeveloper |
---|
|