+ All Categories
Home > Documents > Lector: Aliyev H.U. Lecture №5 Telecommunication network software design with.NET. Using streams...

Lector: Aliyev H.U. Lecture №5 Telecommunication network software design with.NET. Using streams...

Date post: 29-Dec-2015
Category:
Upload: wesley-dickerson
View: 216 times
Download: 0 times
Share this document with a friend
Popular Tags:
18
Lector: Aliyev H.U. Lecture №5 Telecommunication network software design with .NET. Using streams for network programming TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES THE DEPARTMENT OF DATA COMMUNICATION NETWORKS AND SYSTEMS
Transcript

Lector: Aliyev H.U.

Lecture №5Telecommunication network software design with .NET.

Using streams for network programming

TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES

THE DEPARTMENT OFDATA COMMUNICATION NETWORKS AND SYSTEMS

Streams in .NET networking • A stream is an abstract representation of a serial device for storing and

retrieving data one byte at a time- the underlying device can be a file, a printer, or a network socket for example. Through this abstraction, different devices can be accessed with the same process, and similar code can be used to read data from a file input stream as can be used to read data from a network input stream for example. Furthermore, the programmer's need to worry about the actual physical mechanism of the device is removed.

• In this chapter we'll look at the following:• Streams in .NET• The Stream class and its members• The FileStream class and other Stream-derived classes• Reading to and writing from binary and text files• Serialization

Streams in .NET• The .NET Framework provides a rich set of classes for

performing operations on various types of streams. Stream is the main class, an abstract class from which all other stream-related classes derive. Since a stream is an abstraction of data as a sequence of bytes, to manipulate these sequences of bytes you have to perform some basic operations such as reading, writing, or seeking. With the Stream class you can perform binary I/O operations on a stream. With TextReader and TextWriter you can perform character I/O operations, whereas with BinaryReader and BinaryWriter you can perform I/O operations on primitive types.

Synchronous and Asynchronous I/O

• There are two ways to perform operations on a stream, synchronous or asynchronous-your choice will depend upon the requirements of your application. As we will see in a moment, the Stream class provides methods for both synchronous and asynchronous operations, but first let's discuss some of the advantages and disadvantages of each type of operation.

• Synchronous I/O• By default, all operations on streams are performed synchronously-this is the

simplest way to perform I/O operations. The disadvantage of synchronous I/O is that it blocks processing until the I/O operation is complete-then the application is allowed to continue processing.

• Asynchronous I/O• In asynchronous I/O, other tasks can be performed while the I/O operation is being

completed. When the I/O operation completes, the operating system notifies the caller. Therefore, a separate notification mechanism is required for asynchronous I/O.

• This method is useful when an application needs to continue performing other tasks while processing large amounts of data from a stream, or needs to work with slow devices whose rate of access would otherwise slow down the application.

The Stream Class

• The Stream class in the System.IO namespace is the base class for all the other stream classes, and provides the functionality for performing fundamental operations on stream. If you understand the functionality of the Stream class, then you can easily understand the other derived classes too-the key thing is to learn how to create the different types of stream with each class. In short, all the Stream-derived classes represent various types of stream with common or derived methods from the Stream class, and some extra methods for performing operations on that specific type of stream.

• The diagram below illustrates Stream, the derived classes, and various other classes provided for performing operations on stream.

The Stream Class

The main classes derived from Stream

Class Purpose

FileStream Uses files as backing storage. The most widely used Stream class.

BufferedStream Uses a buffer as backing storage. Used as intermediate storage for improving performance.

MemoryStream Uses memory as backing storage and performs faster I/O operations when compared to other streams.

NetworkStream Does not have any backing storage. Used with other streams for transferring data across a network.

CryptoStream CryptoStream is used with other stream classes for performing encryption-decryption on streams.

The NetworkStream Class• Across a network, the data transferred between locations is in

the form of a continuous flow or stream. For handling such streams, .NET has a special class-NetworkStream in the System.Net.Sockets namespace, which is used for sending and receiving data through network sockets.

• NetworkStream is an unbuffered stream and does not support random access to data-you cannot change the position within the stream and therefore the use of Seek() and Position throws an exception. The CanSeek property always returns false for a NetworkStream object.

• As NetworkStream is unbuffered, BufferedStream is usually used along with this class as an intermediate storage me

The important members of NetworkStream

Property Description

DataAvailable Returns a Boolean value indicating whether data is available in the stream for reading or not. A value of true indicates that data is available in the stream.

Readable Used to get or set a Boolean value indicating whether read access is given to the stream or not. This property works in the same way as the CanRead property in other streams.

Socket Returns the underlying Socket.

Writeable Used for checking whether the stream can be written to or not. A value of true indicates that the stream is writeable. This property works in the same way as the CanWrite property in other streams.

The NetworkStream Class• Each NetworkStream constructor requires at least a Socket-in

addition you can specify a Boolean value indicating ownership of a stream and/or a value from the FileAccess enumeration we saw earlier to control read and write permissions. Setting the ownership flag to true gives control of the socket to the NetworkStream object, and by using the Close() method you can close the underlying socket.

• A NetworkStream can also be retrieved from a TcpClient-we'll spend a whole lesson on TCP, but we'll make use of it here to illustrate NetworkStream in a client-server scenario. The TcpClient.Get Stream() method creates a NetworkStream object, passing in its underlying Socket as the constructor parameter.

The code for the TCP client with NS

• using System; • using System.IO; • using System.Text; • using System.Net; • using System.Net.Sockets; • class TcpClient Example • { static void Main(string[] args)• { try • {

• We create our TcpClient, and connect to the localhost on port 5001. Once again, we use the GetStream() method to return the underlying NetworkStream:

The code for the TCP client with NS

• // Create TCP Client • TcpClient client = new TcpClient(); • //Connect using hostname and port client.Connect

("localhost", 5001); • //Get NetworkStream instance for sending data • NetworkStream stm = client.GetStream();

• Now we have our NetworkStream, sending the data is the same process as we have used with the other streams:

The code for the TCP client with NS

• byte[] sendBytes = Encoding.ASCII.GetBytes("This data has come from" + " another place!!!");

• stm.Write (sendBytes, 0, sendBytes.Length);

• Finally, our TcpClient is closed:

• client.Close(); • } • catch (Exception e) • { • Console.WriteLine(e.ToString()); • Console.WriteLine("The listener has probably not started");• } • }• }

Stream Manipulation• We have looked at the different types of streams, how to create

them, and how to read to and write from them. However, we've only been able to read and write byte arrays-this is a somewhat cumbersome way of reading data. For example, if we wanted to write some decimal values to a file, we'd have to break these down into bytes ourselves-there must be an easier way! Sure enough, the System.IO namespace provides classes and methods for manipulating different data types in streams.

• We'll look at the following classes for stream manipulation in this section:

• Manipulating binary files with BinaryReader and BinaryWriter • Manipulating text files with StreamReader and StreamWriter • Before we look at these classes, we need to consider encoding-this is

something that we've alluded to earlier in the chapter when we were converting to and from byte arrays for transferring data from streams.

Encoding String Data• The Encoding class in the System.Text namespace is provided

for performing such operations. The Encoding class handles sets of Unicode characters. Unicode is a worldwide character-encoding standard, which allows universal data exchange and improves multilingual text processing. Many languages cannot be represented without Unicode, such as Japanese. The wider range of characters supported by the Unicode format means that Unicode information typically requires 16-bit space instead of the standard 8-bit character strings.

Encoding classes• The .NET Framework has several classes derived from the

Encoding class for performing encoding between different formats.

Class Use ASCIIEncoding Encodes Unicode characters as single 1-byte ASCII characters. This encoding

has limitations because it supports 7-bit character values and is not a good choice for applications that support multilingual text processing.

UnicodeEncoding Encodes each Unicode character in 2 bytes.

UTF7Encoding Encodes in 7-bit Unicode encoding.UTF (Unicode Translation Format) 7 and 8 are commonly used formats to send Unicode-based data across networks.

UTF8Encoding This class supports 8-bit UTF-8 encoding. This encoding is widely used with applications that support multilingual text processing.XML uses UTF-8 encoding by default.

Serialization

• Serialization is the process of taking objects and converting their state information into a form that can be stored or transported. The stored or transported object can then be deserialized to recreate the original state of the object. Thus you can serialize an object, transmit this information across a network and then restore the object and its original state from another application or system.

• Here are some key areas where serialization is a benefit:• Availability-a component can be saved in a file and can be made available

whenever required.• Lifetime-saving the object with its state increases its life. In normal practice, when

you close an application all associated objects are destroyed automatically. • Use within networked applications-the complex form of the object has been

transformed to a format that is suitable for transferring across a network, and possibly through firewalls.

• Reliability-the saved object can be recreated 'as-it-is'.• In this section we'll be looking at two ways of serializing objects:• Serializing into XML format• Serializing with formatter objects into binary

Q&A?


Recommended