(c) 2002 Visual Studio Magazine 
Fawcette Technical Publications


VB.NET	Listing 1
Move Between Stream Bytes and Strings. The Encoding class's GetBytes method prepares an HTTP request and then transforms the response from a byte array to a string using the GetString method.

Dim tcpClient As New _
	Net.Sockets.TcpClient("www.microsoft.com", 80)
Dim networkStream As _
	System.Net.Sockets.NetworkStream = _
	tcpClient.GetStream()
Dim sendBytes As [Byte]() = _
System.Text.Encoding.ASCII.GetBytes( _
	"GET /default.htm" + ControlChars.CrLf)
networkStream.Write(sendBytes, 0, _
	sendBytes.Length)
' Reads the NetworkStream into a byte buffer.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, _
	CInt(tcpClient.ReceiveBufferSize))
' Returns the data received from the host to the ' ' console.
Dim returndata As String = _
	Encoding.ASCII.GetString(bytes)

VB.NET	Listing 2
Serialize and Deserialize Objects in a Snap. The code establishes a TCP connection between a client and a server. The server creates a class, initializes its state, serializes it, then sends it over the wire back to the client. The client deserializes it and dumps the class's state to the debugger.

Server
Dim s As TcpListener
s = New TcpListener(8080)
s.Start()
Dim tcpClient As TcpClient = s.AcceptTcpClient()
Dim ns As NetworkStream = tcpClient.GetStream()
Dim bsw As New BufferedStream(ns, 2048)
Dim a As New Class1()
a.DateOfBirth = New Date(2000, 12, 12)
a.Name = "john"
Dim fm As New _
	System.Runtime.Serialization.Formatters. _
	Binary.BinaryFormatter()
fm.Serialize(bsw, a)
bsw.Flush()
bsw.Close()

Client
Dim clientsocket As New TcpClient("localhost", _
	8080)
Dim ns As NetworkStream = clientsocket.GetStream()
Dim bfstreamr As New BufferedStream(ns, 2048)
System.Threading.Thread.CurrentThread.Sleep(2000)
Dim fm As New _
	System.Runtime.Serialization.Formatters. _
	Binary.BinaryFormatter()
Dim a As Class1 = CType( _
	fm.Deserialize(bfstreamr), Class1)
Debug.WriteLine(a.Name)
Debug.WriteLine(a.DateOfBirth)


VB.NET	Listing 3
Load XML Documents Efficently. In the first code block the NetworkStream object is passed to a XmlTextReader. In the second one the NetworkStream is passed into the Xmldocument Load method. In both cases the code is compact and efficient because it doesn't create an unnecessary temporary string.

'Load an XmlTextReader with the received data
Dim tcpClient As New _
	Net.Sockets.TcpClient("localhost", 80)
Dim ns As System.Net.Sockets.NetworkStream = _
	tcpClient.GetStream()
Dim xmltextreder As System.Xml.XmlTextReader = _
	New System.Xml.XmlTextReader(ns)
While xmltextreder.Read()
Debug.WriteLine(xmltextreder.Name)
End While
'Load an XmlDocument with the received data
Dim tcpClient As New _
	Net.Sockets.TcpClient("localhost", 80)
Dim ns As System.Net.Sockets.NetworkStream = _
	tcpClient.GetStream()
Dim l_dom As New Xml.XmlDocument()
l_dom.Load(ns)
