15.5. The NetworkStream Class

A network stream is a stream whose backing store is the network. A network stream is the stream used by network sockets to communicate with each other.

To illustrate the use of the NetworkStream class, let's look at a simple client/server chat application in which the server listens to an open socket at a port for incoming messages from the client. The server socket provides hooks for both the incoming network stream and the outgoing network stream. The client sends messages to the server using its version of the network stream. The following code snippet shows how the server end uses NetworkStream:

IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
TcpListener listener = new TcpListener(ipAddress, 1234);
listener.Start();
Socket socket4Client = listener.AcceptSocket();
NetworkStream networkStream = new NetworkStream(socket4Client);

//Do your I/O stuff to chat with the client

The client side of the application would use the NetworkStream this way:

TcpClient client = new TcpClient("localhost", 1234);
NetworkStream networkStream = client.GetStream();
//Do your I/O stuff to chat with the server

So far we've looked at streams, which are wonderful for reading and writing bytes. But sometimes you want to deal with textual data, and the next section introduces readers and writers for achieving text-based reading and writing from streams.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.239.148