PROWAREtech

articles » archived » asp-net » tcp-ip-sockets

ASP.NET: Windows TCP/IP Sockets Programming

An example using the TcpClient class to connect.

Network with other computers including Internet servers. messageToServer should be a valid HTTP/1.0 or HTTP/1.1 request to connect to an Internet server or simply use System.Net.WebClient.

For more information see the .NET TCP/IP Sockets tutorial.

Private Function ConnectToServer(ByVal serverName As String, _
ByVal messageToServer As String, ByVal port As Integer) As String
	Try
		ConnectToServer = ""
		Dim client As New System.Net.Sockets.TcpClient(serverName, port)
		Dim bData As Byte() = System.Text.Encoding.ASCII.GetBytes(messageToServer)
		Dim stream As System.Net.Sockets.NetworkStream = client.GetStream()
		stream.Write(bData, 0, bData.Length)
		bData = New Byte(2048) {}
		Dim bytes As Int32 = stream.Read(bData, 0, bData.Length)
		While bytes > 0
			ConnectToServer &= System.Text.Encoding.ASCII.GetString(bData, 0, bytes)
			bytes = stream.Read(bData, 0, bData.Length)
		End While
		stream.Close()
		client.Close()
	Catch e As ArgumentNullException
		ConnectToServer = "ArgumentNullException"
	Catch e As System.Net.Sockets.SocketException
		ConnectToServer = "SocketException"
	End Try
End Function

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE