Network I/O
Network I/O is generally similar to
file I/O, and both Stream
and
TextReader
types are used to access to data from a
network connection. The System.Net
namespace
contains additional classes that are useful in dealing with common
network protocols such as HTTP, while the
System.Net.Sockets
namespace contains generalized
classes for dealing with network sockets.
To create a connection to a web server,
you will typically use the abstract WebRequest
class and its Create( )
and GetResponse(
)
methods. Create( )
is a static factory
method that returns a new instance of a subclass of
WebRequest
to handle the URL passed in to
Create( )
. GetResponse( )
returns a WebResponse
object, which provides a
method called GetResponseStream( )
. The
GetResponseStream( )
method returns a
Stream
object, which you can wrap in a
TextReader
. As you’ve already
seen, you can use a TextReader
to read from an I/O
stream.
The following code snippet shows a typical sequence for creating a
connection to a network data source and displaying its contents to
the console device. StreamReader
is a concrete
implementation of the abstract TextReader
base
class:
WebRequest request = WebRequest.Create("http://www.oreilly.com/"); WebResponse response = request.GetResponse( ); Stream stream = response.GetResponseStream( ); StreamReader reader = new StreamReader(stream); // Read a line at a time and write it to the console while (reader.Peek( ) != -1) { Console.WriteLine(reader.ReadLine( )); }
Tip
A network ...
Get .NET & XML now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.