3/30/2017
1
Lecture #3
Dept of Electrical and Electronics Engineering
Çukurova University
EEE 448Computer Networks
with
(Network Programming)
Text Book
• Network programming in .NET with C# and VB.NET
Fiach Reid, Elsevier, 2004
Network Programming and C#
• A network program is any application that uses a computer network to transfer information to and from other applications.
– Web browser, email etc.
• The C# language provides you with all the tools necessary to quickly develop network applications.
• C# have a richer set of programming APIs
• Eliminates most of the complexities previously associated with network programming
Networking Namespaces
• System.Messaging– Functionality for MSMQ
• System.Net– Provides access to higher protocols (FTP, HTTP, DNS)
• System.Net.Information– Network information classes providing statistics, interface
information, and ping
• System.Net.Sockets– Light weight wrappers around TCP and UDP sockets
• System.Runtime.Remoting– Provides functionality for high level distributed
programming (similar to RMI)
• System.Web– Provides high level access to HTTP
Namespaces
• Each namespace provides support for a specific group of classes.
• Once, you have located the namespaces that contain the classes you need for your program,
• You must define them in your program to access the classes.
NamespacesNamespace Description of Classes
Microsoft.Win32 Handles events raised by the OS and Registry handling classes
System Base .NET classes that define commonly used data types and data conversions
System.Collections Defines lists, queues, bit arrays, and string collections
System.IO Allows reading and writing on data streams and files
System.Messaging Provides functionality fo MSMQ-Message Queuing
System.Net Provides access to the Windows network functions
System.Net.Sockets Provides access to the Windows sockets (Winsock) interface
System.Runtime.Remoting Provides access to the Windows distributed computing platform
System.Security Provides access to the CLR security permissions system
System.Text Represents ACSII, Unicode, UTF-7, and UTF-8 character encodings
System.Threading Enables multi-threading programming
System.Web.Mail Enables sending mail messages
System.Windows.Forms Creates Windows-based application using the standard Windows graphical interface
3/30/2017
2
Using Strings in C# Programs• One of the most difficult parts of C# programming
is dealing with strings. Many program security holes develop from string buffer overflows,
– in which programmers have used character arrays for strings, and
– hackers place more characters than memory bytes allocated for the string.
• Because many network protocols are concerned with sending and receiving text strings, it’s a good idea to get a handle on using strings properly in C# network programs.
String class
• Microsoft has incorporated two string handling classes into the C# language.
– The String Class
– The StringBuilder Class
• The String constructor is overloaded, providing several ways to create a string variable.
The String ClassThe basic part of string support in C# is the
String class.
The String class allows you to assign a series of characters to a variable and handle the variable in your program as a single unit.
The String class also contains several methods that can be used to perform operations on string objects, such as determining the length of the string and comparing two strings.
The string class - IIConstructor Description
string(char[]) Creates a string from a specified character array
string(char, int) Creates a string from a specified character repeated int number of times
string(char[], int1, int2) Creates a string from a specified character array, starting at position int1 with a length of int2 bytes
string test = "This is a test string";string test2 = test;string anotherTest = new string('a', 10);
String vs string
• As types, System.String and string are
interchangeable.
– In C# string is an alias for System.String.
• We normally don’t need to prefix String with System because most C# programs have the line
using System;
String vs string
using System;
using System.Text;
static void Main(string[] args)
{
string s = "This is a string";
Console.WriteLine(s);
String S = "This is a String";
Console.WriteLine(S);
Console.ReadLine();
}
3/30/2017
3
String Operations
• The String class provides a rich set of operations:– Substring
– Length
– Comparison
• If you need to do it, there is probably a built-in operation for it.
String Function with ToUpper
static void Main(string[] args)
{
String S1 = @"This is a string with a backslash \";
Console.WriteLine (S1);
Console.WriteLine ("Converting S1 to Upper Case");
String S2 = S1.ToUpper();
Console.WriteLine ("Here is the result:");
Console.WriteLine (S2);
Console.ReadLine();
}
The Result Comparing Stringsstatic void Main(string[] args)
{
string S1 = @"This is a string with a backslash \";
Console.WriteLine(S1);
Console.WriteLine("Converting S1 to Upper Case");
string S2 = S1.ToUpper();
Console.WriteLine("Here is the result:");
Console.WriteLine(S2);
int i1 = String.Compare(S1, S2);
Console.WriteLine("Compare(S1, S2) = {0}", i1);
int i2 = String.CompareOrdinal(S1, S2);
Console.WriteLine("CompareOrdinal(S1, S2) = {0}", i2);
Console.ReadLine();
}
Comparing StringsExample for insert and compare string
using System;
using System.Text;
static void Main(string[] args)
{
string test1 = "This is a test string ", test2, test3;
test2 = test1.Insert(15, "application ");
test3 = test1.ToUpper();
Console.WriteLine("test1: '{0}'", test1);
Console.WriteLine("test2: '{0}'", test2);
Console.WriteLine("test3: '{0}'", test3);
if (test1 == test3)
Console.WriteLine("test1 is equal to test3");
else
Console.WriteLine("test1 is not equal to test3");
test2 = test1.Replace("test", "sample");
Console.WriteLine("the new test2: '{0}'", test2);
}
3/30/2017
4
Operations on Strings
• All numeric types provide a Parse static method that converts a string into the numeric value.
String strZip; // Zip code as string
int intZip; // Zip code as integer
...
intZip = int.Parse(strZip);
Will throw an exception if the string is not the representation of a number of the specified type.
tryParse
• Numeric types also have a tryParse method that will not throw an exception when the string is not a valid number.
static void Main(string[] args)
{
String strZip = Console.ReadLine();
int intZip;
if (int.TryParse(strZip, out intZip))
{
Console.WriteLine(strZip + " is a valid integer");
}
else
{
Console.WriteLine(strZip + " is not a valid integer");
}
}
Parsing Integers
Comma Separated Values
• Common way to represent structured data in a text file.
• Example:
Doe,John,1234 Oak St.,Marion,OH,22333
• Frequently used as interchange format for spreadsheet and database programs.
• Mostly split is used for
String.Split Example
static void Main(string[] args)
{
string words = "one,two,three,four";
string[] split;
split = words.Split(',');
foreach (string s in split)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
Note: Char
3/30/2017
5
String.Split Example
static void Main(string[] args)
{
String[] fruits = {"apple", "orange", "grape", "pear"};
String result = String.Join ( ",", fruits);
Console.WriteLine (result);
Console.ReadLine();
}
The String.Join Method
Note: String, not char
The String.Join MethodThe StringBuilder Class
• The StringBuilder class allows you to create and modify strings without the overhead of recreating new strings each time.
• It generates a mutable sequence of characters that can change size dynamically as the string is modified, allocating more memory as required.
StringBuilder ClassesConstructor Description
StringBuilder() Initializes a new default instance with a size of 16
StringBuilder(int) Initializes a new instance with a capacity of int
StringBuilder(string) Initializes a new instance with a default value of string
StringBuilder(int1, int2) Initializes a new instance with a default capacity of int1 and a maximum capacity of int2
StringBuilder(string, int) Initializes a new instance with a default value of string and a capacity of int
StringBuilder(string, int1, int2, int3)
Initializes a new instance with a default value starting at position int1 of string, int2characters long, with a capacity of int3
Adding to stringI. Versiyon
string s1 = "Test ";
for(i = 0; i < 10 ; i++) { s1 += i.ToString(); }
II. Versiyon
StringBuilder s1 = new StringBuilder("Test");
for(i = 0; i < 10 ; i++) { s1.Append(i) }
3/30/2017
6
StringBuilder Exampleusing System;
using System.Text;
static void Main(string[] args)
{
StringBuilder builder = new StringBuilder( "This is an example string that is an example.");
builder.Replace("an", "the"); // Replaces 'an' with 'the'.
Console.WriteLine(builder.ToString());
//
string[] items = { "Cat", "Dog", "Celebrity" };
StringBuilder builder2 = new StringBuilder( "These items are required:").AppendLine();
foreach (string item in items)
{
builder2.Append(item).AppendLine();
}
Console.WriteLine(builder2.ToString());
Console.ReadLine(); }
StringBuilder with Append
using System;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
int number = 1;
sb.AppendFormat("{0}: {1} ", number++, "another string");
Console.WriteLine("{0}", sb);
}
}
}
PART- II
What is Stream?
• Stream is the natural way to transfer data in the computer world
• To read or write a file, we open a stream connected to the file and access the data through the stream
Input stream
Output stream
C# Streams
• Data handling is one of the most important jobs of programs.
• The C# language supplies an interface to assist programmers in moving large chunks of data to and from data objects.
• The data stream allows multiple bytes of data to be transferred simultaneously to a data object so that programs can work on blocks of data instead of having to build data elements one byte at a time.
Streams- II
• Streams can support three fundamental operations:
– Transferring data from a stream to a memory buffer (reading)
– Transferring data from a memory buffer to a stream (writing)
– Searching the stream for a specific byte pattern (seeking)
3/30/2017
7
Streams- III
• The .NET System.IO namespace contains various stream classes that can be used to combine the bytes from a data source into manageable blocks that are easier to manipulate.
• The FileStream class is a good example of using a stream to simplify reading and writing data.
• This class provides a stream interface to easily read and write data to a disk file.
Streams Basics• Streams are used for reading and writing data
into and from devices
• Streams are ordered sequences of bytes
– Provide consecutive access to its elements
• Different types of streams are available to access different data sources:
– File access, network access, memory streams and
others
• Streams are open before using them and closed after that
Stream Class
• It is an abstract class from which different classes are being derived
• Some of its derived classes are:– MemoryStream
– BufferedStream
– FileStream
– NetworkStream (System.Net.Sockets)
– CryptoStream (System.Security.Cryptography )
MemoryStream class
• This class is used to read and write data to memory
• Some of the methods of MemoryStream are:
Method Description
Read() Used to read the MemoryStream and write the value to the buffer.
ReadByte() Used to read a byte from the MemoryStream
Write() Used to write values from the buffer into the MemoryStream
WriteByte() Used to write a byte to the MemoryStream from the buffer.
WriteTo() Used to write contents of one memory stream into another.
BufferedStream Class
• It is used to read and write to the buffer
• It has two overloaded constructors with following syntax:
//constructor type 1
public BufferedStream(Stream StName);
//constructor type 2
public BufferedStream(Stream StName, int bsize);
Example.
using System.IO;
.
static void Main(string[] args)
{
MemoryStream mS = new MemoryStream(); // Creating empty MemoryStream
byte[] memData = Encoding.UTF8.GetBytes("Will write to memory");
mS.Write(memData, 0, memData.Length); // The data is written position from 0
mS.Position = 0;
byte[] inData = new byte[100];
mS.Read(inData, 0, 100); // reading from memoryStream
Console.WriteLine(Encoding.UTF8.GetString(inData));
Stream strm = new FileStream(@"I:\MemOutput.txt", FileMode.OpenOrCreate, FileAccess.Write);
mS.WriteTo(strm);
Console.ReadLine();
}
3/30/2017
8
BufferedStream Class - Example
using System;
using System.IO;
public class MemoryStreamDemo
{
public static void Main()
{
MemoryStream memstr = new MemoryStream();
BufferedStream buffstr = new BufferedStream (memstr);
buffstr.WriteByte((byte)100);
buffstr.Position =0;
byte[] arrb= {1, 2, 3};
buffstr.Read(arrb,0,2);
Console.WriteLine("The contents of the array are: " +
arrb[0].ToString()) );
}
// OR
BufferedStream Class - Output
for (int i=0;i<3;i++)
{
Console.WriteLine("{0}",arrb[i]);
}
Console.WriteLine("The return value for ReadByte() is {0}",
buffstr.ReadByte());
}
}
FileStream Class
• This class is used to perform read and write operations on files
• Read() and Write() methods are applied for synchronous read and write operations
• BeginRead() and BeginWrite() methods are used for asynchronous read and write operations
• The default mode in the FileStream class is synchronous read/write operations
• It needs using System.IO
FileStream Class Constructors
Constructors Description
FileStream(string FilePath, FileMode)
Takes in the path of the file to be read from or written to and any one of the FileMode enumerator values as its arguments.
FileStream(string FilePath, FileMode, FileAccess)
Takes in the path of the file to be readfrom or written to, any one of the FileModeenumerator values and FileAccessenumerator values as it arguments
FileStream(string FilePath, FileMode, FileAccess, FileShare)
Takes in the path of the file to be readfrom or written to, any one of the FileModeenumerator values, FileAccess enumeratorvalues and any one of the FileShareenumerator values as it arguments.
Reading a Text Fileusing System.IO;
...
static void Main(string[] args)
{
String Input_Line;
StreamReader Reader = new StreamReader(@"c:\test.txt");
while ((Input_Line = Reader.ReadLine()) != null)
{
Console.WriteLine(Input_Line);
}
Console.ReadLine();
}
FileStream Class Exampleusing System.IO;
using System.Text;
public static void Main()
{Console.WriteLine ("Enter the text file name");
string fname = Console.ReadLine();
StreamReader sr = new StreamReader(fname) ;
string line;
while ((line = sr.ReadLine())!= null){ Console.WriteLine (line);}
Console.WriteLine("");
sr.Close();
FileStream filestr = new
FileStream(fname,FileMode.Append,FileAccess.Write,FileShare.Write)
;
filestr.Close();
StreamWriter sw = new StreamWriter(fname, true, Encoding.ASCII);
string NextLine = "This is the appended line.";
sw.Write(NextLine);
sw.Close();
Console.WriteLine ("Appended one line into the file");
}
3/30/2017
9
FileStream Class - Output Mode : OpenOrCreateusing System;
using System.IO;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
FileStream f = new FileStream("I:\\b.txt", FileMode.OpenOrCreate);
f.WriteByte(65); //writing byte into stream
f.Close(); //closing stream
}
}
}
Read Byte-Example
using System;
using System.IO;
public class FileStreamExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("I:\\b.txt", FileMode.OpenOrCreate);
int i = 0;
while ((i = f.ReadByte()) != -1)
{
Console.Write((char)i);
}
f.Close();
}
} 51
Methods of StreamWriter
Method Description
Write() Used to write a character from the stream and move the current position to the next character.
WriteLine() Writes a sequence of a line of characters to the stream. It adds a line terminator to mark the end of the string.
Writing a Text File
static void Main(string[] args){String[] text_array = new String[4];text_array[0] = "This is the first line";text_array[1] = "This is the second line";text_array[2] = "Line \t with \t some \t tabs";text_array[3] = @"Line with a backslash \";
StreamWriter Writer = new StreamWriter(@"I:\test.txt");
foreach (String S in text_array){
Writer.WriteLine(S);}
Writer.Close();Console.WriteLine (@"File I:\test.txt written");Console.ReadLine();
}
Running Text File Demo Program
3/30/2017
10
Example of StreamWriter classstatic void Main(string[] args)
{//Create object of FileInfo for specified path FileStream file = new FileStream(@"I:\MyFile.txt", FileMode.Create);
Console.WriteLine("File can be read : " + file.CanRead);Console.WriteLine("File can be written : " + file.CanWrite);Console.WriteLine("File can be seeked : " + file.CanSeek);
file.WriteByte(150);file.WriteByte(200);
byte[] byteblock = { 10, 20, 30, 40, 50, 60, 70 };
file.Write(byteblock, 0, byteblock.Length);Console.WriteLine("File Length : {0} ", file.Length);Console.WriteLine("File Position : {0} ", file.Position);
file.Position = 0;
Console.WriteLine("File Bytes : {0}", Convert.ToChar(file.ReadByte()) );Console.WriteLine("Second Byte: " + Convert.ToChar(file.ReadByte()));
Console.WriteLine(file.Read(byteblock, 0, byteblock.Length));Console.WriteLine(file.Read(byteblock, 0, byteblock.Length));
Console.ReadLine();}
Asynchusing System;
using System.IO;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
public static async void AsynchReadWrite()
{
FileStream file = new FileStream(@"I:\MyFile.txt", FileMode.Create);
Console.WriteLine("File created");
byte[] byteblock = { 10, 20, 30, 40, 50, 60, 70 };
await file.WriteAsync(byteblock, 0, byteblock.Length);
file.Position = 0;
Console.WriteLine(await file.ReadAsync(byteblock, 0, byteblock.Length));
Console.ReadLine();
}
public static void Main()
{
AsynchReadWrite();
Console.ReadLine();
} } }
What is File Exception?
• Exceptions tell that something unusual was happened, e. g. error or unexpected event
• IOException
• FileNotFoundException
• I/O operations throw exceptions when operation cannot be performed (e.g. missing file)
– When an exception is thrown, all operations after it are not processed
Catching Exceptions
• Catch block specifies the type of exceptions that is caught
– If catch doesn’t specify its type, it catches all types of exceptions
try
{
StreamReader reader = new StreamReader("somefile.txt");
Console.WriteLine("File successfully open.");
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("Can not find 'somefile.txt'.");
}
Handling Exceptions When Opening a Filetry{
StreamReader streamReader = new StreamReader("c:\\NotExistingFileName.txt");
}catch (NullReferenceException exc){
Console.WriteLine(exc.Message);}catch (FileNotFoundException exc){
Console.WriteLine("File {0} is not found!", exc.FileName);
}catch{
Console.WriteLine("Fatal error occurred.");}
Network Stream
• NetworkStream implements the standard .NET Framework stream mechanism to send and receive data through network sockets.
• NetworkStream supports both synchronous and asynchronous access to the network data stream.
• NetworkStream does not support random access to the network data stream.
3/30/2017
11
Server Example...
using System.Net.Sockets;
.
static void Main(string[] args)
{
try {
// TCP listener oluşturuluyor.
TcpListener listener = new TcpListener(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }), 6006);
listener.Start();
Console.WriteLine("TcpListener is established that is waiting for CLIENT");
TcpClient tc = listener.AcceptTcpClient();
NetworkStream stm = tc.GetStream();
byte[] readBuf = new byte[100];
stm.Read(readBuf, 0, 100);
// Veriler görüntüleniyor.
Console.WriteLine(Encoding.UTF8.GetString(readBuf));
stm.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
} }
Client.
using System.Net.Sockets; // CLIENT
.
static void Main(string[] args)
{
try {
TcpClient client = new TcpClient(); // TCP Client oluşturuluyor.
// Hostname ve port bilgileri kullanılarak listener'a bağlanılıyor.
client.Connect("localhost", 6006); // Verileri göndermek için NetworkStream instance'ı oluştu.
NetworkStream stm = client.GetStream();
byte[] sendBytes = Encoding.UTF8.GetBytes("This data is sent to Server from Client Application");
stm.Write(sendBytes, 0, sendBytes.Length);
client.Close();
Console.WriteLine("Tcp client sent the data.!!!!!!!!");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.WriteLine("Probably, Server is not active to listen client yet");
}
}
Crypto Stream
• The CryptoStream class is another composable stream that enables an application to encrypt and decrypt data to and from another stream.
• System.Security.Cryptography namespace
• In cryptography, two different techniques are used to encrypt and decrypt data:
– A symmetric and
– An asymmetric cryptography.
using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Net.Sockets;
....
static void Main(string[] args) {
Console.WriteLine("For CryptoStream, Choose one of Service Providers :\n");
Console.WriteLine("1 = DESCryptoServiceProvider");
Console.WriteLine("2 = RC2CryptoServiceProvider");
Console.WriteLine("3 = RijndaelManaged");
Console.WriteLine("4 = TripleBESCryptoServiceProvider");
Console.WriteLine("5 = SymmetricAlgorithm");
SymmetricAlgorithm des = null;
switch (Console.ReadLine())
{
case "1": des = new DESCryptoServiceProvider(); break;
case "2": des = new RC2CryptoServiceProvider(); break;
case "3": des = new RijndaelManaged(); break;
case "4": des = new TripleDESCryptoServiceProvider(); break;
case "5": des = SymmetricAlgorithm.Create(); break;
}
Continue - I
FileStream fs = new FileStream(@"I:\TopSecret.txt", FileMode.Create, FileAccess.Write);
ICryptoTransform desencrypt = des.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fs, desencrypt, CryptoStreamMode.Write);
string theMessage = "Top Scret Message";
byte[] bytearrayinput = Encoding.UTF8.GetBytes(theMessage);
Console.WriteLine("Orjinal Mesaj : {0} ", theMessage);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fs.Close();
Continue-II// Decrypt işlemi
FileStream fsread = new FileStream(@"I:\TopSecret.txt", FileMode.Open, FileAccess.ReadWrite);
byte[] encByte = new byte[fsread.Length];
fsread.Read(encByte, 0, encByte.Length);
Console.WriteLine("Encrypt edilmiş mesaj : " + Encoding.UTF8.GetString(encByte));
fsread.Position = 0;
ICryptoTransform desdecrypt = des.CreateDecryptor();
CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
byte[] decrByte = new byte[fsread.Length];
cryptostreamDecr.Read(decrByte, 0, (int)fsread.Length);
string output = Encoding.UTF8.GetString(decrByte);
Console.WriteLine("Decrypted edilmiş mesaj : {0}", output);
cryptostreamDecr.Close();
fsread.Close();
Console.ReadLine();
} } }
3/30/2017
12
• http://csharp.net-informations.com/communications/csharp-socket-programming.htm