Sunteți pe pagina 1din 50

Laborator

Programare C# - Rețele de Calculatoare

1. Structuri fundamentale de control


a. Citirea unui string de la tastatura de la tastatura
static void Main(string[] args)
{
Console.Write ("Enter Your First Name : ");
string name1 = Console.ReadLine ();
Console.Write ("Enter Your Last Name : ");
string name2 = Console.ReadLine ();
Console.WriteLine ("Hello Mr." + name1 +" " + name2);
Console.ReadLine ();
}

b. Citirea unor intregi de la tastatura. Efectuare de calcule

static void Main(string[] args)


{
int a,b;
string s1 = string.Empty;
string s2 = string.Empty;
Console.Write("Enter no 1 # "); // Afiseaza cererea pentru
numarul 1
s1 = Console.ReadLine (); // salveaza numarul in variabila
string s1
a = int.Parse (s1); // stringul s1 este convertit intr-o
variabila de tip int
Console.Write("Enter no 2 # "); //Afiseaza cererea pentru
numarul 2
s2 = Console.ReadLine(); // salveaza numarul in variabila
string s2
b = int.Parse(s2); // stringul s2 este convertit intr-o
variabila de tip int
Console.WriteLine(""); // Linie goala
Console.WriteLine("********************* Rezultatul
calculelor **********************");
Console.WriteLine("");
// Calcule
Console.WriteLine("No1 + No2 = " + (a+b));
Console.WriteLine("No1 - No2 = " + (a-b));
Console.WriteLine("No1 / No2 = " + (a/b));
Console.WriteLine("No1 * No2 = " + (a*b));
Console.WriteLine("No1 % No2 = " + a%b));
Console.ReadLine();
}
c. Transformarea gradelor Fahrenheit în Celsius

static void Main(string[] args)


{
float fahrenheit, celsius;
string s;
Console.Write("Introduceti temperatura in Fahrenheit ");
s = Console.ReadLine();
fahrenheit = float.Parse(s);
celsius = (float)((fahrenheit - 32) / 1.8);
Console.WriteLine("Temperatura in celsius = " + celsius);
Console.ReadLine();
}

d. Calculul distantei parcurse, daca se cunosc viteza initiala (m/s), timpul deplasării
(sec.) şi acceleratia(m/s2).

static void Main(string[] args)


{
float distance,u,t,a;
string u1,t1,a1,reply;
a. u = viteza initiala
b. t = interval timp
c. a = acceleratie
d. reply valoare folosita pentru a verifica daca programul
trebuie repornit cu diferite valori
int replyforrestart,counter;
e. replyforrestart va lua valoarea 0 sau 1
f. 1 = restart , 0 = exit
g. counter este folosit pentru a seta de cate ori sunt
setate datele
Console.WriteLine("******** Vom calcula distanta parcursa
de un vehicul **********");
counter = 1;
h. La prima rulare a programului, counter = 1
startfromhere: // Programul va reporni de aici cand sunt
necesare noi valori
distance = u = t = a = 0.0F; //resetam toate valorile pe 0
Console.WriteLine(""); // Linie goala
Console.WriteLine("Numar setare = " + counter); // Afisarea
numarului de setari facute
Console.WriteLine("");
Console.Write("Introduceti intervalul de timp (t) : ");
t1 = Console.ReadLine();
t = float.Parse(t1);
Console.Write("Introduceti viteza initiala (u) : ");
u1 = Console.ReadLine();
u = float.Parse(u1);
Console.Write("Introduceti acceleratia (a) : ");
a1 = Console.ReadLine();
a = float.Parse(a1);
distance = u*t + a*t*t/2;
Console.WriteLine("Distanta parcursa de vehicul = " +
distance);
Console.WriteLine("");
Console.Write("Doriti recalcularea pentru alte valori? (1
pentru Da / 0 pentru Exit) ? : ");
reply = Console.ReadLine();
replyforrestart = int.Parse(reply);
if (replyforrestart == 1)
{
counter = counter+ 1;
Console.WriteLine("");
Console.WriteLine(" ***************************** ");
goto startfromhere;
}
else
{
/ Nu trebuie facut nimic ....programul se inchide
}
}
e. Să se calculeze în acelaşi program: suma numerelor pare/impare de la 1 la 20,
suma numerelor divizibile cu 7 între 100 şi 200, câte numere sunt divizibile cu 7
intre 100 şi 200

static void Main(string[] args)

int x=0, suma_impare=0, suma_pare=0, suma_div7 = 0


,totalno7 = 0, i;
/ "suma_impare" va contine suma numerelor impare intre 1 - 20

/ "suma_pare" va contine suma numerelor pare intre 1 - 20


/ "suma_div7" va contine suma numerelor intre 100 - 200
divizibile 7
/ "totalno7" va contine cate numere intre 100 - 200 sunt
divizibile cu 7
/ "i" contor folosit in cicluri
/ "x" este o variabila temporara, prin care se verifica
conditiile impuse
for (i=0 ; i<=20 ; i++)

x = i % 2;

if (x != 0)

suma_impare = suma_impare + i;

if (x == 0)

{
suma_pare = suma_pare + i;

//calculul sumei numerelor divizibile cu 7 si numararea lor


x = 0; // resetam valoarea lui x

for (i=100; i<=200;i++)

x = i % 7;

if (x == 0)

suma_div7 = suma_div7 + i;

totalno7 = totalno7 + 1;

Console.WriteLine("Suma numerelor impare intre 1 - 20 = " +


suma_impare + "\n");
Console.WriteLine("Suma numerelor pare intre 1 si 20 = " +
suma_pare + "\n");

Console.WriteLine("Suma numerelor divizibile cu 7 intre 100 si


200 = " + suma_div7 + "\n");

Console.WriteLine("Totalul numerelor divizibile cu 7 intre 100 si


200 = " + totalno7 + "\n");

Console.ReadLine();

Exercitii propuse:
1. Rescrieti programul c pentru transformarea temperaturii din grade Celsius in grade
Fahrenheit
2. Realizati modificarile necesare in programul d, astfel incat viteza sa fie introdusa in
kilometri pe ora, iar distanta sa fie afisata in kilometri
3. Realizati modificarile necesare in problema e pentru introducerea de la tastatura a
capetelor de interval. Se vor efectua aceleasi operatii, dar se va afisa in plus totalul
numerelor divizibile cu trei – dintre cele două capete de interval.
2. Structuri fundamentale de control, structure de date: vectori
unidimensionale

a. Se initializeaza un vector cu note ale studentilor. Sa se calculeze numarul de note pe


fiecare interval 1-4, 4-5, 5-6, 6-7, 7-8, 8-9, 9-10. Sa se calculeze media notelor intre 1
si 10. Sa se calculeze media pentru un interval specificat de utilizator

static void Main(string[] args)


{
int i, note1_ 4 = 0, note4_5 = 0, note5_6 = 0, note6_7 =
0, note7_8 = 0, note8_9 = 0, note9_10 = 0, note_imposibile = 0;
float [] note =
{3.7F,4.5F,8,10,9.2F,2,2,7,6,9,5,4,3,1,5.7F,6.3F,10,10,1,7,6.8F,7,9,2,4,8,10,
8.5F,7,8,12};
float medie = 0;
for (i = 0; i < note.Length; i++) {
if (note[i] >= 1 && note[i] <= 4)
{
note1_4 = note1_4 + 1;
continue;
}
else if (note[i] > 4 && note[i] <= 5)
{
note4_5 = note4_5 + 1;
continue;
}
else if (note[i] > 5 && note[i] <= 6)
{
note5_6 = note5_6 + 1;
continue;
}
else if (note[i] > 6 && note[i] <= 7)
{
note6_7 = note6_7 + 1;
continue;
}
else if (note[i] > 7 && note[i] <= 8)
{
note7_8 = note7_8 + 1;
continue;
}
else if (note[i] > 8 && note[i] <= 9)
{
note8_9 = note8_9 + 1;
continue;
}
else if (note[i] > 9 && note[i] <= 10)
{
note9_10 = note9_10 + 1;
continue;
}
else
{
note_imposibile = note_imposibile + 1;
continue;
}
}

medie = calculeazaMedie(note);
Console.WriteLine("Note intre 1-4 : " + note1_4);
Console.WriteLine("Note intre 4-5 : " + note4_5);
Console.WriteLine("Note intre 5-6 : " + note5_6);
Console.WriteLine("Note intre 6-7 : " + note6_7);
Console.WriteLine("Note intre 7-8 : " + note7_8);
Console.WriteLine("Note intre 8-9 : " + note8_9);
Console.WriteLine("Note intre 9-10 : " + note9_10);
Console.WriteLine("Note imposibile : " + note_imposibile);
Console.WriteLine("Media notelor intre 1 si 10 varianta 1 este:
" + medie);
medie = calculeazaMedie_v2(note);
Console.WriteLine("Media notelor intre 1 si 10 varianta 2 este:
" + medie);
medie = calculeazaMedie_v3(8,10,note);
Console.WriteLine("Media notelor intre 8 si 10 este: " + medie);
Console.ReadLine();
}

// metoda 1 foreach
static float calculeazaMedie(float[] temp_vector)
{
float medie = 0;
int count = 0;
float suma_elemente = 0;
foreach (float f in temp_vector)
{
if (f >= 1 && f <= 10)
{
count++;
suma_elemente = suma_elemente + f;
}
}
medie = suma_elemente / count;
return medie;
}

// metoda 2: for
static float calculeazaMedie_v2(float[] temp_vector)
{
float medie = 0;
int count = 0;
float suma_elemente = 0;
for (int i = 0; i < temp_vector.Length; i++ )
{
if (temp_vector[i] >= 1 && temp_vector[i] <= 10)
{
count++;
suma_elemente = suma_elemente + temp_vector[i];
}
}
medie = suma_elemente / count;
return medie;
}

static float calculeazaMedie_v3(int limita_minima, int limita_maxima,


float [] tempVector)
{
int count = 0;
float medie = 0;
float suma = 0;
foreach (float f in tempVector)
{
if (f >= limita_minima && f < limita_maxima)
{
count++;
suma = suma + f;
}
}
medie = suma / count;
return medie;
}

b. Impartirea unui string in cuvinte. Cautarea numarului de aparitii ale unui


cuvant in cadrul unui string

class Program
{
static void Main(string[] args)
{
# region declaratii_si_initializari_variabile

string s = string.Empty; // Declararea unui string


string cuvant_cautat = string.Empty;
Console.Write("Introduceti stringul : ");
int numar_aparitii_cuvant = 0;

#endregion

s = Console.ReadLine(); // Citirea stringului si salvarea in s'


string[] cuvinte = s.Split(' ');
Console.Write("Introduceti cuvantul cautat: ");
cuvant_cautat = Console.ReadLine();
/ 'cuvinte' reprezinta un vector de stringuri
/ stringul 's' va fi impartit in substringuri la intalnirea unui
caracter din setcaractere
/ fiecare substring va fi salvat in vectorul cuvinte
int i = cuvinte.Length; //Dimensiunea vectorului cuvinte
numar_aparitii_cuvant = cautaCuvant(cuvant_cautat, cuvinte);
Console.WriteLine("The total number of words in the entered
string : " + i);
Console.WriteLine("Cuvantul: " + cuvant_cautat + " a aparut de: "
+ numar_aparitii_cuvant);
Console.ReadLine();
}

static int cautaCuvant(string cuvant, string[] vector_cuvinte)


{
int numar_aparitii = 0;
foreach (string temp_string in vector_cuvinte)
{
if (formateazaCuvant(temp_string) == cuvant)
{
numar_aparitii++;
}
}
return numar_aparitii;
}
static string formateazaCuvant(string cuvant)
{
string cuvantFinal = cuvant;
if (cuvant.EndsWith(","))
{
cuvantFinal = cuvant.Remove(cuvant.Length - 1);
}
return cuvantFinal;
}
}

c. Sa se calculeze si sa se afiseze numerele din seria Fibonnaci

static void Main(string[] args)


{
int first = 1, second = 1, third, no, count = 0;
long sum = 2;
Console.Write("Enter the number uptill which you want the
fibonacci numbers :");
no = int.Parse(Console.ReadLine());
if (no >= 45)
{
Console.WriteLine("\n Numarul nu trebuie sa depaseasca 45 : "
+ sum);
}
else
{
Console.Write("Fibonacci Series : 1 1");
do
{
third = first + second;
Console.Write(" " + third);
first = second;

second = third;
count = count + 1;
sum = sum + third;
}
while ((count + 3) <= no);
Console.WriteLine("\nSum of all fibonacci digits : " + sum);
}
}
d. Sa se copie elementele a doi vectori intr-un al treilea vector. Sa se ordoneze vectorul
destinatie. Sa se inverseze valorile vectorului destinatie

static void Main(string[] args)


{
int[] A = { 127, 157, 240, 550, 510 };
int[] B = { 275, 157, 750, 255, 150, 209, 1, 4 , 7 };
int CLength = (A.Length + B.Length);
int[] C = new int[CLength];
int contor_C = 0;
int[] Vector_Destinatie = new int[CLength];

# region metoda 1

for (int i = 0; i < A.Length; i++)


{
C[i] = A[i];
contor_C = i;
}
contor_C = contor_C + 1;
for (int j = 0; j < B.Length; j++)
{
C[contor_C] = B[j];
contor_C = contor_C + 1;
}

#endregion

#region metoda 2

Array.Sort(C);
Array.Copy(A,0,Vector_Destinatie,0,A.Length);
Array.Copy(B, 0, Vector_Destinatie, A.Length, B.Length);

#endregion

#region diferite metode din clasa vector


Array.Sort(Vector_Destinatie);
int pozitie_numar = Array.IndexOf(Vector_Destinatie,550);
pozitie_numar = Array.LastIndexOf(Vector_Destinatie, 550);
pozitie_numar = Array.BinarySearch(Vector_Destinatie, 550);
Array.Reverse(Vector_Destinatie);
#endregion
Console.ReadLine();
}
3. Clase: Membri, Proprietăți, Constructori, Interfață

a. Să se realizeze o aplicaţie pentru gestiunea angajaţilor dintr-o companie

Pasul 1: Definirea structurii de clase: Clasa Angajat

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Gestiune.Clase
{
class Angajat
{
#region campuri

private string _nume = string.Empty;


private string _prenume = string.Empty;
private double _salariu = 0;
private string _datanasterii = string.Empty;
private string _dataangajarii = string.Empty;

#endregion

#region constructori

public Angajat()
{
_salariu = 800;
_datanasterii = "01.01.1990";
_dataangajarii = "01.01.1990";
}

public Angajat(string nume, string prenume, double


salariu, string datanasterii, string dataangajarii )
{
_nume = nume;
_prenume = prenume;
_salariu = salariu;
_datanasterii = datanasterii;
_dataangajarii = dataangajarii;
}
public Angajat(string nume, string prenume):this()
{
_nume = nume;
_prenume = prenume;
}

#endregion

#region proprietati

public string Nume


{
get { return _nume; }
set { _nume = value; }
}

public string Prenume


{
get { return _prenume; }

set { _prenume = value; }


}

public double Salariu


{
get { return _salariu; }
set { if (value < 10000) { _salariu = value; } else {
Console.WriteLine("Salariul trebuie sa fie mai mic de 10000"); } }
}

public string DataNasterii


{
get { return _datanasterii; }
set { _datanasterii = value; }
}

public string DataAngajarii


{
get { return _dataangajarii; }
set { _dataangajarii = value; }
}

#endregion

#region interfata_clasei

public void CresteSalariu(int procent)


{
_salariu = _salariu + (_salariu * procent/100);
}

public void ScadeSalariu(int procent)


{
_salariu = _salariu - (_salariu * procent / 100);
}
public string DetaliiCompleteAngajat(string nume, string
prenume, double salariu, string datanasterii, string
dataangajarii)
{
string detalii_complete = string.Empty;

detalii_complete = "Angajatul cu numele: " + nume + " " + prenume


+ ",nascut pe data: " + datanasterii + " si angajat incepand cu "
+ dataangajarii + " are salariul: " + salariu;
return detalii_complete;
}

public string DetaliiCompleteAngajat(Angajat angajat)


{
string detalii_complete = string.Empty;
detalii_complete = "Angajatul cu numele: " + angajat.Nume + " " +
angajat.Prenume + ",nascut pe data: " + angajat.DataNasterii + " si
angajat incepand cu " + angajat.DataAngajarii + " are salariul: "
+ angajat.Salariu;
return detalii_complete;
}

#endregion
}
}

Pasul 2: Utilizarea structurii de clase în programul Principal


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gestiune.Clase;
using System.Collections;

namespace Gestiune
{
class Program
{
static void Main(string[] args)
{

#region declaratii şi iniţializări

ArrayList listaAngajati = new ArrayList();


Angajat[] listaAngajati_2 = new Angajat[10];
List<Angajat> listaAngajati_3 = new List<Angajat>();
//obiect de tip Random utilizat in determinarea unui index
aleator cu valori intre 0 si numarul de angajati existent intr-o lista
Random randomAngajat = new Random();
int indexAngajatNorocos = 0;

#endregion

#region construire obiecte de tip angajat

//construire obiect angajat1 prin constructor implicit


//initalizare proprietati
Angajat angajat1 = new Angajat();
angajat1.DataAngajarii = "15.01.1998";
angajat1.DataNasterii = "14.02.1976";
angajat1.Nume = "Mircea";
angajat1.Prenume = "Adrian";
//se va afisa faptul ca salariul
trebuie sa fie mai mic de
10000 //este pastrata valoarea
implicita 800
angajat1.Salariu = 10002;

//construire obiect angajat2,3,4 prin constructor parametrizat -


sunt initializate toate
campurile
Angajat angajat2 = new Angajat("Cristina", "Mantu", 2500,
"10.07.1970", "19.04.2004");

Angajat angajat3 = new Angajat("Teodor", "Cristian", 2700,


"12.05.1974", "20.06.2002");

Angajat angajat4 = new Angajat("Matache", "Gavrila", 1700,


"15.11.1979", "20.01.2002");

//construire obiect angajat2,3,4 prin constructor parametrizat - este


initializat un singur
camp
Angajat angajat5 = new Angajat("Gavrila", "Marian");

#endregion

#region afişare_date_angajaţi

//afisare date angajat 1


Console.WriteLine("Numele
angajatului 1 este: " +
angajat1.Nume);
Console.WriteLine();
Console.WriteLine("Prenumele angajatului
1 este: " + angajat1.Prenume);
Console.WriteLine();
Console.WriteLine("Salariul angajatului 1
este: " + angajat1.Salariu);
Console.WriteLine();
Console.WriteLine("Data Nasterii angajatului 1
este: " + angajat1.DataNasterii);
Console.WriteLine();
Console.WriteLine("Data Angajarii angajatului 1
este: " + angajat1.DataAngajarii);
Console.WriteLine();
//afisare date angajat 1 prin apelul metodelor din interfata
clasei Angajat
Console.WriteLine("Detaliile angajatului 1: " +
angajat1.DetaliiCompleteAngajat(angajat1));
Console.WriteLine();
Console.WriteLine("Detaliile angajatului 1: " +
angajat1.DetaliiCompleteAngajat(angajat1.Nume, angajat1.Prenume,
angajat1.Salariu, angajat1.DataNasterii, angajat1.DataAngajarii));
Console.WriteLine();

#endregion

//cresterea salariului angajatului 1


Console.WriteLine("Salariul angajatului 1 este inainte de
crestere : " + angajat1.Salariu); angajat1.CresteSalariu(12);
Console.WriteLine("Salariul angajatului 1 este dupa crestere : " +
angajat1.Salariu);

//scaderea salariului angajatului 1


Console.WriteLine("Salariul angajatului 1 este inainte de
scadere : " + angajat1.Salariu); angajat1.ScadeSalariu(10);
Console.WriteLine("Salariul angajatului 1 este dupa scadere : " +
angajat1.Salariu);

#region contruire_lista_angajati

// construirea unor liste cu angajati


//utilizam un obiect de tip ArrayList: structura
dinamica ...poate stoca orice tip
listaAngajati.Add(angajat1);
listaAngajati.Add(angajat2);
listaAngajati.Add(angajat3);
listaAngajati.Add(angajat4);
listaAngajati.Add(angajat5);
//utilizam un vector de angajati - dimensiune fixa,
poate stoca obiecte de acelasi tip for (int i=0; i<=4;
i++)
{
switch (i)
{
case 0:
listaAngajati_2[i] = angajat1;
break;

case 1:
listaAngajati_2[i] = angajat2;
break;
case 2:
listaAngajati_2[i] = angajat3;
break;
case 3:
listaAngajati_2[i] = angajat4;
break;
case 4:
listaAngajati_2[i] = angajat5;
break;
}
}

//utilizam un generic List<TIP> - structura


dinamica, obligativitate pe tip
listaAngajati_3.Add(angajat1);
listaAngajati_3.Add(angajat2);
listaAngajati_3.Add(angajat3);
listaAngajati_3.Add(angajat4);
listaAngajati_3.Add(angajat5);

#endregion

#region afisare_detalii angajati

//afisam detaliile angajatilor din ArrayList

//utilizand foreach
foreach (Angajat ang in listaAngajati)
{
Console.WriteLine("Detaliile angajatului: " +
ang.DetaliiCompleteAngajat(ang));
Console.WriteLine();
}

//utilizand for
for (int i = 0; i < listaAngajati.Count; i++)
{
//Trebuie sa realizam conversia obiectului
listaAngajati[i] in tipul Angajat
Console.WriteLine("Detaliile angajatului " +
(i+1) + " sunt: " +
((Angajat)listaAngajati[i]).DetaliiCompleteAngajat((Angajat)listaAngajati[i]))
;
Console.WriteLine();
}

//afisam primii doi angajati din vector

for (int i = 0; i <= 1; i++)


{
Console.WriteLine("Detaliile
angajatului " + (i+1) + " sunt: " +
listaAngajati_2[i].DetaliiCompleteAngajat(listaAng
ajati_2[i]));
Console.WriteLine();
}

//afisam ultimii doi angajati din List<TIP>


for (int i = listaAngajati_3.Count - 2; i < listaAngajati_3.Count;
i++)
{
Console.WriteLine("Detaliile
angajatului " + (i + 1) + " sunt: " +
listaAngajati_3[i].DetaliiCompleteAngajat(listaAngaj
ati_3[i]));
Console.WriteLine();
}

#endregion

#region premierea_unui_angajat_norocos
indexAngajatNorocos =
randomAngajat.Next(listaAngajati_3.
Count);
listaAngajati_3[indexAngajatNorocos
].CresteSalariu(8);
Console.WriteLine("Angajatul norocos este: " + listaAngajati_
3[indexAngajatNorocos].Nume + " " +
listaAngajati_3[indexAngajatNorocos].Prenume + ", noul salariu fiind: " +
listaAngajati_3[indexAngajatNorocos].Salariu);
#endregion

Console.ReadLine();
}
}
}

4. Moștenire și Polimorfism
a. Să se realizeze o aplicaţie pentru gestiunea angajaţilor, clientilor si furnizorilor unei
companii (continuare exercițiu precedent)

Etapa 1: Definirea clasei parinte: Companie


class Companie
{
private string _denumire = string.Empty;
private string _telefon = string.Empty;
private string _adresa = string.Empty;

public Companie()
{
}

public Companie(string denumire, string telefon, string adresa)


{
_denumire = denumire;
_telefon = telefon;
_adresa = telefon;
}

public string Denumire


{
get { return _denumire; }
set { _denumire = value; }
}

public string Telefon


{
get { return _telefon; }
set { _telefon = value; }
}

public string Adresa


{
get { return _adresa; }
set { _adresa = value; }
}
#region functii_helper

protected string Formateaza_Detalii_Companie(Companie companie)


{
string detalii_companie = string.Empty;
detalii_companie = "Compania cu numele-" + companie.Denumire + "
are adresa-" + companie.Adresa + " si telefonul-" + companie.Telefon;
return detalii_companie;
}

#endregion

#region interfata clasa

public void TrimiteEmail (Companie companie)


{
Console.WriteLine("Nu se poate transmite mesaj catre compania-" +
companie.Denumire + ". A fost transmis un mesaj postal la adresa: " +
companie.Adresa);
}

public virtual int GenereazaRaport (Companie companie)


{
Console.WriteLine("A fost generat raportul pentru compania: " +
companie.Denumire + " ......");
Console.WriteLine("Caracteristicile companiei " +
companie.Denumire + " sunt: Telefonul este:" + companie.Telefon + " " +
"Adresa Companiei este: " + companie.Adresa);
return 1;
}
#endregion
}
Etapa 2: Definirea clasei derivata: Client
class Client:Companie
{
private string _observatii = string.Empty;
private string _adresaWeb = string.Empty;
private string _adresaEmail = string.Empty;
private string _denumire = string.Empty;
private string _adresa = string.Empty;
private string _telefon = string.Empty;

public Client()
{
}

public Client(string observatii, string adresaWeb, string


adresaEmail, string denumire, string telefon, string adresa):
base(denumire,telefon,adresa)
{
_observatii = observatii;
_adresaEmail = adresaEmail;
_adresaWeb = adresaWeb;
}

public string Observatii


{
get { return _observatii; }
set { _observatii = value; }

public string AdresaWeb


{
get { return _adresaWeb; }
set { _adresaWeb = value; }
}

public string AdresaEmail


{
get { return _adresaEmail; }
set { _adresaEmail = value; }
}

#region interfata_clasei

public void TrimiteEmail(Client client)


{
Console.WriteLine("A fost transmis cu succes mesajul catre
clientul-" + client.Denumire + " la adresa: " + client.AdresaEmail);
}

public override int GenereazaRaport(Companie companie)


{
Client client = companie as Client;
Console.WriteLine("A fost generat raportul pentru clientul: " +
companie.Denumire + " ......");
Console.WriteLine("Caracteristicile clientului-" + client.Denumire +
" sunt: Adresa web este:" + client.AdresaWeb + " " + "Adresa Email este: " +
client.AdresaEmail + " iar observatiile asupra lui: "
+ client.Observatii);
return 1;
}
#endregion
}

Etapa 3: Definirea clasei derivata: Furnizor

class Furnizor:Companie
{
private string _datainfiintare = string.Empty;
private string _adresaWeb = string.Empty;
private string _adresaEmail = string.Empty;

public Furnizor()
{
}

public Furnizor(string data_infiintare, string adresa_web, string


adresa_email)
{
_datainfiintare = data_infiintare;
_adresaWeb = adresa_web;
_adresaEmail = adresa_email;
}
public string DataInfiintare
{
get { return _datainfiintare; }
set { _datainfiintare = value; }
}

public string AdresaWeb


{
get { return _adresaWeb; }
set { _adresaWeb = value; }
}

public string AdresaEmail


{
get { return _adresaEmail; }
set { _adresaEmail = value; }
}

#region interfata clasei

public void TrimiteEmail(Furnizor furnizor)


{
Console.WriteLine("A fost transmis cu succes mesajul catre
furnizorul-" + furnizor.Denumire + " la adresa: " + furnizor.AdresaEmail);
}

public string DetaliiFurnizor(Furnizor furnizor)


{
string detaliiFurnizor =
furnizor.Formateaza_Detalii_Companie(furnizor);
return detaliiFurnizor;
}

//functie test transmitere prin referinta


public void modFurnizor(Furnizor furnizor)
{
furnizor.DataInfiintare = "";
furnizor.AdresaEmail = "";
furnizor.AdresaWeb = "";
}

//functie test transmitere prin valoare


public void modValoare(int x)
{
x = 8;
}

public override int GenereazaRaport(Companie companie)


{
Furnizor furnizor = companie as Furnizor;
Console.WriteLine("A fost generat raportul pentru furnizorul: " +
companie.Denumire + " ......");
Console.WriteLine("Caracteristicile furnizorului " +
furnizor.Denumire + " sunt: Adresa web este:" + furnizor.AdresaWeb + " " +
"Adresa Email este: " + furnizor.AdresaEmail + " Data infiintarii este: " +
furnizor.DataInfiintare);
return 1;
}

#endregion
}

Etapa 4: Utilizarea claselor: Companie, Client, Furnizor in programul principal


#region utilizare_functii_polimorfice
Console.WriteLine("******************************************
POLIMORFISM *********************************");
Console.WriteLine("******************************************
POLIMORFISM *********************************");
Companie companie1 = new Companie();
companie1.Adresa = "Strada Domneasca, Nr 15, Galati";
companie1.Denumire = "Alpha SRL";
companie1.Telefon = "416567";
Companie companie2 = new Companie();
companie2.Adresa = "Strada Marmureni, Nr 15, Iasi";
companie2.Denumire = "Beta SA";
companie2.Telefon = "425394";
Companie companie3 = new Companie();
Furnizor furnizor1 = new Furnizor();
furnizor1.Adresa = "Strada Poporului, Nr 13, Bucuresti";
furnizor1.Telefon = "567423";
furnizor1.Denumire = "Piritex SRL";
furnizor1.AdresaWeb = "www.piritex.com";
furnizor1.AdresaEmail = "piritex@yahoo.com";

Furnizor furnizor2 = new Furnizor();


furnizor2.Adresa = "Strada Basarabiei, Nr 23, Galati";
furnizor2.Telefon = "223344";
furnizor2.Denumire = "Xerox SA";
furnizor2.AdresaWeb = "www.xerox.com";
furnizor2.AdresaEmail = "xerox@yahoo.com"; string
x = furnizor1.DetaliiFurnizor(furnizor1);

#region exemplu transmitere parametri prin referinta


//este transmisa adresa obiectului furnizor, modificarile sunt
facute pe obiectul in sine
//in urma apelului acestei functii, denumirea si cele doua adrese
vor fi vide
furnizor1.modFurnizor(furnizor1);
furnizor1.Denumire = "Piritex SRL";
furnizor1.AdresaWeb = "www.piritex.com";
furnizor1.AdresaEmail = "piritex@yahoo.com";
#endregion
#region exemplu transmitere parametri prin valoare
//este transmisa o copie, modificarile nu sunt
int y = 20;
furnizor1.modValoare(y);
#endregion

Client client1 = new Client("Client fara probleme",


"www.pancronex.ro", "panc@pancronex.ro", "Pancronex", "124389", "Strada
Floreasca, Nr. 12, Bucuresti");
Client client2 = new Client("Probleme la achitarea facturilor",
"www.adian.ro", "adi@adian.ro", "Adian SRL", "986543", "Strada Mantulesti,
Nr. 7, Timisoara");

List<Companie> listaCompanii = new List<Companie>();


listaCompanii.Add(companie1);
listaCompanii.Add(companie2);
listaCompanii.Add(furnizor1);
listaCompanii.Add(furnizor2);
listaCompanii.Add(client1);
listaCompanii.Add(client2);

foreach (Companie comp in listaCompanii)


{
comp.GenereazaRaport(comp);
}
#endregion

#region apelare metoda clasa derivata, fara folosirea


polimorfismului

Console.WriteLine("******************ALTERNATIVA LA POLIMORFISM!
*********************************");
Console.WriteLine("**************** ALTERNATIVA LA POLIMORFISM!
*********************************");

foreach (Companie companie in listaCompanii)


{
switch (companie.GetType().ToString())
{
case "Gestiune.Clase.Companie":
companie.TrimiteEmail(companie);
break;
case "Gestiune.Clase.Client":
Client client = companie as Client;
client.TrimiteEmail(client);
break;
case "Gestiune.Clase.Furnizor":
Furnizor furnizor = companie as Furnizor;
furnizor.TrimiteEmail(furnizor);
break;
default:
break;
}
}
#endregion

Să se realizeze un program, conform specificatiilor prezentate in cartea „Beginning C sharp


2008”, scrisa de Jack Purdum, pagina 445-463
5. C# - File Streams

a. Read and write files using StreamWriter and StreamReader Class


FileStream fs = new FileStream(@"c:\test.txt", FileMode.Create);
StreamWriter w = new StreamWriter(fs, Encoding.UTF8);
w.WriteLine(1.2M);
w.WriteLine("string"); w.WriteLine('!'); w.WriteLine('?'); w.Flush();
w.Close(); fs.Close();

fs = new FileStream(@"c:\test.txt", FileMode.Open);


StreamReader r = new StreamReader(fs, Encoding.UTF8);
Console.WriteLine(Decimal.Parse(r.ReadLine()));
Console.WriteLine(r.ReadLine());
Console.WriteLine(Char.Parse(r.ReadLine()));
Console.WriteLine(Char.Parse(r.ReadLine())); r.Close();
fs.Close(); Console.ReadLine();

b. Read ASCII string from byte buffer


FileStream file = File.OpenRead(@"c:\test.txt");
byte[] buffer = new byte[1024];
int c = file.Read(buffer, 0,
buffer.Length); while (c > 0)
{
Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetSt
ring(buffer)); c = file.Read(buffer, 0, buffer.Length);
}
file.Close();

c. Reads and displays bytes until end-of-file


Stream input = new FileStream(@"c:\test.txt", FileMode.Open);
int i;
while ((i = input.ReadByte()) != -1)
Console.Write(i + " ");
input.Close();
Console.ReadLin
e();

d. Write string to a text file


StreamWriter sw = new StreamWriter("practice.txt");
sw.Write("www.google.com");
sw.Close();

e. Read text file line by line with exception catch


string
strLine;
try
{
FileStream aFile = new FileStream("books.xml",
FileMode.Open); StreamReader sr = new
StreamReader(aFile);
strLine = sr.ReadLine();
while (strLine != null)
{
Console.WriteLine(strLine);
strLine = sr.ReadLine();
}
aFile.Close();
sr.Close();
Console.ReadLine();
}
catch (IOException e)
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(e.ToString()); Console.ReadLine();
return;
}
return;

f. Text file Write with format and write boolean value to a text file

try
{
FileStream aFile = new
FileStream("practice.txt",FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
bool truth = true;
sw.WriteLine("A");
sw.WriteLine("{0}",System.DateTime.Now.ToShortDateString());
sw.Write("A");
sw.Write("www.java2s.com",truth);
sw.Close();
}
catch(IOException e)
{
Console.WriteLine("An IO exception has been
thrown!"); Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
return;

g. Read and write to a file

FileInfo f = new
FileInfo(@"C:\Bar.txt");
FileStream fs = f.Create();
StreamWriter w = new
StreamWriter(fs); w.Write("Hello
World");
w.Close();
fs = f.Open(FileMode.Open, FileAccess.Read,
FileShare.None); StreamReader r = new
StreamReader(fs);
string t;
while ((t = r.ReadLine()) != null)
{
Console.WriteLine(t);
}
w.Close();
fs.Close();
f.Delete();

h. Get Disk Attributes


FileInfo file = new FileInfo("c:\\VO.log");
// Display drive information.
DriveInfo drv = new DriveInfo(file.FullName);
Console.WriteLine("Drive name: " + drv.Name);
Console.WriteLine("Available disk space on: " +
drv.AvailableFreeSpace);
Console.WriteLine("File system type is: " + drv.DriveFormat);
Console.WriteLine("Available disk space: " +
drv.AvailableFreeSpace);
Console.WriteLine("Drive type: " +
drv.DriveType); Console.ReadLine();

i. Using StringReader and StringWriter


// Create a StringWriter
StringWriter strwtr = new StringWriter();
/ Write to StringWriter.
for (int i = 0; i < 10; i++)
strwtr.WriteLine("This is i:
" + i);
/ Create a StringReader

/ Now, read from


StringReader. string str
= strrdr.ReadLine();
while (str != null)
{
str =
strrdr.ReadLine();
Console.WriteLine(s
tr);

j. Demonstrates manipulating a string read as a line from a file


a. Create a stream object and open the input file
FileStream istream;
try
{
istream = new FileStream(@"c:\sample.txt", FileMode.Open,
FileAccess.Read);
/ Associate a reader with the stream
StreamReader reader = new
StreamReader(istream);
/ Declare a new StringBuilder
/ Counter for the lines
int Lines = 0;
while (reader.Peek() > 0)
{
++Lines;
/ Clear out the string
builder strb.Length = 0;
/ Read a line from the file
string str = reader.ReadLine();
/ Split the line into words
string[] Data = str.Split(new char[] { ' ' });
/ Build the output line to show line, word and character
count strb.AppendFormat("Line {0} contains {1} words and {2}
characters:\r\n{3}",

/ Write the string to the


console
Console.WriteLine(strb.ToStr
ing());
}
istream.Close();
}
catch (Exception)
{
Console.WriteLine("Could not open sample.txt for reading");
}

k. Creating memory streams


MemoryStream m = new MemoryStream(64);
Console.WriteLine("Length: {0}\tPosition: {1}\tCapacity: {2}",
m.Length, m.Position, m.Capacity);
for (int i = 0; i < 64; i++)
{
m.WriteByte((byte)i);
}
Console.WriteLine("Length: {0}\tPosition: {1}\tCapacity: {2}",
m.Length, m.Position, m.Capacity);
byte[] ba = m.GetBuffer();
foreach (byte b in ba)
{
Console.Write("{0,-3}", b);
}
m.Close();

l. Write into a memory stream


MemoryStream memOut = new MemoryStream();
byte[] bs = { 1, 2, 3, 4, 5, 6 };
memOut.Write(bs, 0, bs.Length);
memOut.Seek(+3, SeekOrigin.Begin);
byte b = (byte)memOut.ReadByte();
Console.WriteLine("Value: " + b);
m. Copying files
int i;
FileStream
fin;
FileStream
fout; try
{
fin = new FileStream(@"c:\IDK.xls", FileMode.Open);
}
catch (FileNotFoundException exc)
{
Console.WriteLine(exc.Message + "\nInput File
Not Found"); return;
}
try
{
fout = new FileStream(@"c:\IDK1.xls", FileMode.OpenOrCreate);
}
catch (IOException exc)
{
Console.WriteLine(exc.Message + "\nError Opening
Output File"); return;
}
try
{
do
{
i = fin.ReadByte();
if (i != -1)
fout.WriteByte((byte)i);
} while (i != -1);
}
catch (IOException exc)
{
Console.WriteLine(exc.Message + "File Error");
}

fin.Close();
fout.Close();

n. Writing data: copying from one stream to another


using (Stream from = new FileStream(@"c:\IDK.xls", FileMode.Open))
using (Stream to = new FileStream(@"c:\\IDK2.xls",
FileMode.OpenOrCreate))
{
int readCount;
byte[] buffer = new byte[1024];
while ((readCount = from.Read(buffer, 0, 1024)) != 0)
{
to.Write(buffer, 0, readCount);
}
}

o. Create FileStream from FileInfo


FileInfo f = new
FileInfo("Bar.txt");
FileStream fs = f.Create();
StreamWriter w = new
StreamWriter(fs);
w.Write("Hello World");
w.Close();
fs = f.Open(FileMode.Open, FileAccess.Read,
FileShare.None); StreamReader r = new
StreamReader(fs);
string t;
while ((t = r.ReadLine())
!= null){
Console.WriteLine(t);
}
w.Close();
fs.Close();
f.Delete();

p. Read license key from a file and display it on a console


String line = "";
FileInfo license = new
FileInfo("c:\\LICENSE.txt"); try
{
StreamReader txtIn = license.OpenText();
do
{
line = txtIn.ReadLine();
Console.WriteLine("Your license code
is: " + line); } while (line != null);
}
catch (FileNotFoundException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("MAKE SURE LICENSE.TXT IS PRESENT ON
DRIVE C");
}
finally
{
Console.WriteLine("You don't need a license code");
}

q. Get file Creation time from FileInfo


string[] cla = Environment.GetCommandLineArgs();
if (cla.GetUpperBound(0) == 2)
{
FileInfo fi = new FileInfo(cla[1]);
fi.MoveTo(cla[2]);
Console.WriteLine("File Created : " +
fi.CreationTime.ToString());
Console.WriteLine("Moved to : " + cla[2]);
}
else
Console.WriteLine("Usage: mv <source file> <destination
file>");

r. Get Last updated, accessed and write time


FileInfo file = new FileInfo("c:\\a.txt");
Console.WriteLine("Checking file: " +
file.Name); Console.WriteLine("File exists: "
+ file.Exists.ToString()); if (file.Exists) {
Console.Write("File created: ");
Console.WriteLine(file.CreationTime.ToString());
Console.Write("File last updated: ");
Console.WriteLine(file.LastWriteTime.ToString());
Console.Write("File last accessed: ");
Console.WriteLine(file.LastAccessTime.ToString());
Console.Write("File size (bytes): ");
Console.WriteLine(file.Length.ToString());
Console.Write("File attribute list: ");
Console.WriteLine(file.Attributes.ToString());
}

s. Copying A File by using FileInfo


FileInfo MyFile = new
FileInfo(@"c:\Projects\Testing.txt");
MyFile.Create();
MyFile.CopyTo(@"c:\Folder\Testing.txt");
//or
MyFile.CopyTo(@"c:\Folder\Testing.txt", true);

t. Deleting files
FileInfo MyFile = new
FileInfo(@"c:\Projects\Testing.txt");
MyFile.Create();
MyFile.Delete();
6. Network programming in .NET Framework

The network interface is not directly accessible in order to send and receive packets. We
need an intermediary connector to handle the programming interface to the network. A
socket represents a connector that connects an application to the network interface. In order
to send and receive data, we must call socket’s methods.
'System.Net.Sockets' namespace contains the classes needed by .NET for accessing the low-
level Winsock APIs. Network programming involves common concepts like the IP address
and port. IP address is a unique identifier of a computer on a network and port is like a gate
through which applications communicate with each other.
When the application needs to communicate with a remote computer or a device over the
network, we should know its IP address. Afterwards, a gate (Port) must be opened to that IP
and then send and receive the required data.
 .NET defines two classes in the System.Net namespace to handle various types of IP address
information:
 IPAddress (IPAddress newaddress = IPAddress.Parse("192.168.1.1");
 IPEndPoint (represent a specific IP address/port combination. An IPEndPoint object
is used when binding sockets to local addresses, or when connecting sockets to remote
addresses.)

There are two types of network communication: connection-oriented and connectionless.


In a connection-oriented socket, the TCP protocol is used to establish a session
(connection) between two IP address endpoints and the data can be reliably transferred
between the devices. Connectionless sockets use the UDP protocol. No connection
information is required to be sent between the network devices and it is often difficult to
determine which device is acting as a "server", and which is acting as a "client".

For creating a connection-oriented socket, separate sequences of functions must be used for
server programs and client programs:

Figure 1: Server-Client communication


For the server application, there are four tasks to be performed before the server can
transfer data with a client connection:

1. Create a socket.
2. Bind the socket to a local IPEndPoint.
3. Place the socket in listen mode.
4. Accept an incoming connection on the socket.

1. IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8000);


2. Socket newsock = Socket(AddressFamily.InterNetwork,
3. SocketType.Stream, ProtocolType.Tcp);
4. newsock.Bind(localEndPoint);
5. newsock.Listen(10);
6. Socket client = newsock.Accept();

As for the client, the first step is to create a Socket object. The Socket object can be used by
the socket Connect() method to connect the socket to a remote host:

1. IPEndPoint ipep = new IPEndPoint(Ipaddress.Parse("127.0.0.1"), 8000);


2. Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,
ProtocolType.Tcp);
3. server.Connect(ipep);

a. The following example program creates a server that receives connection requests from
clients. The server is built with a synchronous socket, so execution of the server
application is suspended while it waits for a connection from a client. The application
receives a string from the client, displays the string on the console, and then echoes the
string back to the client. The string from the client must contain the string "<EOF>" to
signal the end of the message.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketListener


{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}

The following example program creates a client that connects to a server. The client is
built with a synchronous socket, so execution of the client application is suspended until
the server returns a response. The application sends a string to the server and then
displays the string returned by the server on the console.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketClient


{
public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartClient();
Console.ReadLine();
return 0;
}
}
b. Implement a program to transfer files between two network computers

The server
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace FileServer
{
class Program
{
static void Main(string[] args)
{
Server s = new Server();
s.StartServer();
}
}

public class Server


{
IPEndPoint ipEnd;
Socket sock;
public Server()
{
//create ipaddress ipendpoint tcp listener, bind socket to ipendpoint
IPAddress sIp = IPAddress.Parse("127.0.0.1");
ipEnd = new IPEndPoint(sIp, 5656);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP);
sock.Bind(ipEnd);
}
public void StartServer()
{
try
{
Console.WriteLine("Starting...");
Console.WriteLine("Running and waiting to receive file.");
while (true)
{
sock.Listen(100);
Socket clientSock = sock.Accept();
Console.WriteLine("Client connected");
//prepare structure for fileNameLength
byte[] fileNameLen = new byte[4];
//receive fileNameLength
int receivedBytesLen0 = clientSock.Receive((fileNameLen));
int no_of_bytes_in_filename = BitConverter.ToInt32(fileNameLen,
0);
//prepare structure for name of the file
byte[] name_of_the_file = new byte[no_of_bytes_in_filename];
//receive name of the file
int receivedBytesLen1 = clientSock.Receive((name_of_the_file));
//decode filename from byte[]
string file_name =
System.Text.Encoding.ASCII.GetString(name_of_the_file);
//prepare structure for message length
byte[] messageLen = new byte[4];
//receive message length
int receivedBytesLen2 = clientSock.Receive((messageLen));
int no_of_bytes_in_message = BitConverter.ToInt32(messageLen, 0);
//prepare structure for file data
byte[] message_content = new byte[no_of_bytes_in_message];
//receive real file data
int receivedBytesLen13 = clientSock.Receive((message_content));
//get the fileName from the full path
string fileName = "c:\\Temp\\" + Path.GetFileName(file_name);
try
{
//write to folder
File.WriteAllBytes(@fileName, message_content);
}
catch (Exception ex) { }
//close socket
clientSock.Close();
Console.WriteLine("Received & Saved file!");
}
}
catch (Exception ex) { }
}
}
}

The client
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FileClient
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo dir = new DirectoryInfo(@"C:\SourceFolder");
List<string> file_names = new List<string>();
file_names.Clear();
file_names = DirSearch(@"C:\SourceFolder");
{
foreach (string file in file_names)
{
Console.WriteLine("Sending file {0}", file);
Client.SendFile(file);
}
}
}
static List<string> DirSearch(string sDir)
{
List<string> file_names = new List<string>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
file_names.Add(f);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return file_names;
}
}
public class Client
{
public static string currentMsg = "Idle";
public static void SendFile(string fileName)
{
try
{
//block current thread for 5 seconds
Thread.Sleep(5000);
//create socket and ip endpoint
IPEndPoint ipEnd = CreateIPEndPoint("127.0.0.1:5656");
Socket clientSock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
string filePath = "";
//encode name of the file
byte[] name_of_the_file = Encoding.ASCII.GetBytes(fileName);
//encode fileName Length
byte[] fileNameLen = BitConverter.GetBytes(name_of_the_file.Length);
//encode fileContent
byte[] fileData = File.ReadAllBytes(filePath + fileName);
// econde number of bytes in message
byte[] noBytesInMessage = BitConverter.GetBytes(fileData.Count());
//encode fileName
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] fileNameBytes = encoding.GetBytes(fileName);
// connect to server
clientSock.Connect(ipEnd);
//send fileName length
clientSock.Send(fileNameLen);
// send fileName
clientSock.Send(name_of_the_file);
// send numberofBytes in file
clientSock.Send(noBytesInMessage);
Console.WriteLine("start sending file...");
//send file data
clientSock.Send(fileData);
Console.WriteLine("File {0} was sent", fileName);
Console.WriteLine("Disconnecting...");
//close socket
clientSock.Close();
Console.WriteLine("File transferred.");
}
catch (Exception ex)
{
if (ex.Message == "No connection could be made")
currentMsg = "File Sending fail. Because server not running.";
else currentMsg = "File Sending fail." + ex.Message;
}
}
public static IPEndPoint CreateIPEndPoint(string endPoint)
{
string[] ep = endPoint.Split(':');
if (ep.Length < 2) throw new FormatException("Invalid endpoint format");
IPAddress ip;
if (ep.Length > 2)
{
if (!IPAddress.TryParse(string.Join(":", ep, 0, ep.Length - 1), out
ip))
{
throw new FormatException("Invalid ip-adress");
}
}
else
{
if (!IPAddress.TryParse(ep[0], out ip))
{
throw new FormatException("Invalid ip-adress");
}
}
int port;
if (!int.TryParse(ep[ep.Length - 1], NumberStyles.None,
NumberFormatInfo.CurrentInfo, out port))
{
throw new FormatException("Invalid port");
}
return new IPEndPoint(ip, port);
}
}
}

c. Using TCP-UDP services

The TcpClient class requests data from an Internet resource using TCP. The methods and
properties of TcpClient abstract the details for creating a Socket for requesting and receiving
data using TCP. Because the connection to the remote device is represented as a stream, data
can be read and written with .NET Framework stream-handling techniques.

The TCP protocol establishes a connection with a remote endpoint and then uses that
connection to send and receive data packets. TCP is responsible for ensuring that data packets
are sent to the endpoint and assembled in the correct order when they arrive.

To establish a TCP connection, you must know the address of the network device hosting the
service you need and you must know the TCP port that the service uses to communicate. The
Internet Assigned Numbers Authority (Iana) defines port numbers for common services (see
www.iana.org/assignments/port-numbers). Services not on the Iana list can have port
numbers in the range 1,024 to 65,535.

The following example demonstrates creating a network time server using


a TcpListener to monitor TCP port 13. When an incoming connection request is
accepted, the time server responds with the current date and time from the host server.
using System;
using System.Net.Sockets;
using System.Text;
public class TcpTimeServer
{
private const int portNum = 13;
public static int Main(String[] args)
{
bool done = false;
TcpListener listener = new TcpListener(portNum);
listener.Start();
while (!done)
{
Console.Write("Waiting for connection...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
NetworkStream ns = client.GetStream();
byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
try
{
ns.Write(byteTime, 0, byteTime.Length);
ns.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
listener.Stop();
return 0;
}
}

The following example demonstrates setting up a TcpClient to connect to a time server


on TCP port 13.

using System;
using System.Net.Sockets;
using System.Text;
public class TcpTimeClient
{
private const int portNum = 13;
private const string hostName = "localhost";
public static int Main(String[] args)
{
try
{
TcpClient client = new TcpClient(hostName, portNum);
NetworkStream ns = client.GetStream();
byte[] bytes = new byte[1024];
int bytesRead = ns.Read(bytes, 0, bytes.Length);
Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytesRead));
client.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return 0;
}
}

d. Objects serialization and sending over the network

Employee Server

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class EmployeeSrvr
{
public static void Main()
{
byte[] data = new byte[1024];
TcpListener server = new TcpListener(9050);
server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream ns = client.GetStream();
byte[] size = new byte[2];
int recv = ns.Read(size, 0, 2);
int packsize = BitConverter.ToInt16(size, 0);
Console.WriteLine("packet size = {0}", packsize);
recv = ns.Read(data, 0, packsize);
Employee emp1 = new Employee(data);
Console.WriteLine("emp1.EmployeeID = {0}", emp1.EmployeeID);
Console.WriteLine("emp1.LastName = {0}", emp1.LastName);
Console.WriteLine("emp1.FirstName = {0}", emp1.FirstName);
Console.WriteLine("emp1.YearsService = {0}", emp1.YearsService);
Console.WriteLine("emp1.Salary = {0}\n", emp1.Salary);
size = new byte[2];
recv = ns.Read(size, 0, 2);
packsize = BitConverter.ToInt16(size, 0);
data = new byte[packsize];
Console.WriteLine("packet size = {0}", packsize);
recv = ns.Read(data, 0, packsize);
Employee emp2 = new Employee(data);
Console.WriteLine("emp2.EmployeeID = {0}", emp2.EmployeeID);
Console.WriteLine("emp2.LastName = {0}", emp2.LastName);
Console.WriteLine("emp2.FirstName = {0}", emp2.FirstName);
Console.WriteLine("emp2.YearsService = {0}", emp2.YearsService);
Console.WriteLine("emp2.Salary = {0}", emp2.Salary);
ns.Close();
client.Close();
server.Stop();
Console.ReadLine();
}
}
public class Employee
{
public int EmployeeID;
private int LastNameSize;
public string LastName;
private int FirstNameSize;
public string FirstName;
public int YearsService;
public double Salary;
public int size;
public Employee()
{
}
public Employee(byte[] data)
{
int place = 0;
EmployeeID = BitConverter.ToInt32(data, place);
place += 4;
LastNameSize = BitConverter.ToInt32(data, place);
place += 4;
LastName = Encoding.ASCII.GetString(data, place, LastNameSize);
place = place + LastNameSize;
FirstNameSize = BitConverter.ToInt32(data, place);
place += 4;
FirstName = Encoding.ASCII.GetString(data, place, FirstNameSize);
place += FirstNameSize;
YearsService = BitConverter.ToInt32(data, place);
place += 4;
Salary = BitConverter.ToDouble(data, place);
}
public byte[] GetBytes()
{
byte[] data = new byte[1024];
int place = 0;
Buffer.BlockCopy(BitConverter.GetBytes(EmployeeID), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(BitConverter.GetBytes(LastName.Length), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(Encoding.ASCII.GetBytes(LastName), 0, data, place,
LastName.Length);
place += LastName.Length;
Buffer.BlockCopy(BitConverter.GetBytes(FirstName.Length), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(Encoding.ASCII.GetBytes(FirstName), 0, data, place,
FirstName.Length);
place += FirstName.Length;
Buffer.BlockCopy(BitConverter.GetBytes(YearsService), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(BitConverter.GetBytes(Salary), 0, data, place, 8);
place += 8;
size = place;
return data;
}
}

Employee Client
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

public class EmployeeClient


{
public static void Main()
{
Employee emp1 = new Employee();
Employee emp2 = new Employee();
TcpClient client;
emp1.EmployeeID = 1;
emp1.LastName = "Blum";
emp1.FirstName = "Katie Jane";
emp1.YearsService = 12;
emp1.Salary = 35000.50;
emp2.EmployeeID = 2;
emp2.LastName = "Blum";
emp2.FirstName = "Jessica";
emp2.YearsService = 9;
emp2.Salary = 23700.30;
try
{
client = new TcpClient("127.0.0.1", 9050);
}
catch (SocketException)
{
Console.WriteLine("Unable to connect to server");
return;
}
NetworkStream ns = client.GetStream();
byte[] data = emp1.GetBytes();
int size = emp1.size;
byte[] packsize = new byte[2];
Console.WriteLine("packet size = {0}", size);
packsize = BitConverter.GetBytes(size);
ns.Write(packsize, 0, 2);
ns.Write(data, 0, size);
ns.Flush();
data = emp2.GetBytes();
size = emp2.size;
packsize = new byte[2];
Console.WriteLine("packet size = {0}", size);
packsize = BitConverter.GetBytes(size);
ns.Write(packsize, 0, 2);
ns.Write(data, 0, size);
ns.Flush();
ns.Close();
client.Close();
}
}
public class Employee
{
public int EmployeeID;
private int LastNameSize;
public string LastName;
private int FirstNameSize;
public string FirstName;
public int YearsService;
public double Salary;
public int size;
public Employee()
{
}
public Employee(byte[] data)
{
int place = 0;
EmployeeID = BitConverter.ToInt32(data, place);
place += 4;
LastNameSize = BitConverter.ToInt32(data, place);
place += 4;
LastName = Encoding.ASCII.GetString(data, place, LastNameSize);
place = place + LastNameSize;
FirstNameSize = BitConverter.ToInt32(data, place);
place += 4;
FirstName = Encoding.ASCII.GetString(data, place, FirstNameSize);
place += FirstNameSize;
YearsService = BitConverter.ToInt32(data, place);
place += 4;
Salary = BitConverter.ToDouble(data, place);
}
public byte[] GetBytes()
{
byte[] data = new byte[1024];
int place = 0;
Buffer.BlockCopy(BitConverter.GetBytes(EmployeeID), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(BitConverter.GetBytes(LastName.Length), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(Encoding.ASCII.GetBytes(LastName), 0, data, place,
LastName.Length);
place += LastName.Length;
Buffer.BlockCopy(BitConverter.GetBytes(FirstName.Length), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(Encoding.ASCII.GetBytes(FirstName), 0, data, place,
FirstName.Length);
place += FirstName.Length;
Buffer.BlockCopy(BitConverter.GetBytes(YearsService), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(BitConverter.GetBytes(Salary), 0, data, place, 8);
place += 8;
size = place;
return data;
}
}

e. Building a chat application: server & client

Building the server


using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Chat Server Started ....");
counter = 0;
while ((true))
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[65536];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = Encoding.Default.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0,
dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Joined ", dataFromClient, false);
Console.WriteLine(dataFromClient + " Joined chat room ");
handleClient client = new handleClient();
client.startClient(clientSocket, dataFromClient, clientsList);
}
}
public static void broadcast(string msg, string uName, bool flag)
{
foreach (DictionaryEntry Item in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)Item.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " +
msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
} //end broadcast function
}//end Main class
public class handleClient
{
TcpClient clientSocket;
string clNo;
Hashtable clientsList;
public void startClient(TcpClient inClientSocket, string clineNo, Hashtable
cList)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
this.clientsList = cList;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[65536];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0,
(int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0,
dataFromClient.IndexOf("$"));
Console.WriteLine("From client - " + clNo + " : " +
dataFromClient);
rCount = Convert.ToString(requestCount);
Program.broadcast(dataFromClient, clNo, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}//end while
}//end doChat
} //end class handleClinet
}//end namespace

Building the client

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ClientChat
{
public partial class Form1 : Form
{
TcpClient clientSocket = new TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox1.Text +
"$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
private void button1_Click(object sender, EventArgs e)
{
readData = "Conected to Chat Server ...";
msg();
clientSocket.Connect("127.0.0.1", 8888);
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.Text +
"$");
string x = Encoding.Default.GetString(outStream);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
private void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[65536];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
msg();
}
}
private void msg()
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(msg));
else
textBox2.Text = textBox2.Text + Environment.NewLine + " >> " +
readData;
}
}
}

f. Building a web server


using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

public class HttpFileServer : IDisposable


{
private readonly string rootPath;
private const int bufferSize = 1024 * 512; //512KB
private readonly HttpListener http;
public HttpFileServer(string rootPath)
{
this.rootPath = rootPath;
http = new HttpListener();
http.Prefixes.Add("http://localhost:8889/");
http.Start();
http.BeginGetContext(requestWait, null);
}
public void Dispose()
{
http.Stop();
}
private void requestWait(IAsyncResult ar)
{
if (!http.IsListening)
return;
var c = http.EndGetContext(ar);
http.BeginGetContext(requestWait, null);
var url = tuneUrl(c.Request.RawUrl);
var fullPath = string.IsNullOrEmpty(url) ? rootPath : Path.Combine(rootPath,
url);
if (Directory.Exists(fullPath))
returnDirContents(c, fullPath);
else if (File.Exists(fullPath))
returnFile(c, fullPath);
else
return404(c);
}
private void returnDirContents(HttpListenerContext context, string dirPath)
{

context.Response.ContentType = "text/html";
context.Response.ContentEncoding = Encoding.UTF8;
using (var sw = new StreamWriter(context.Response.OutputStream))
{
sw.WriteLine("<html>");
sw.WriteLine("<head><meta http-equiv=\"Content-Type\" content=\"text/html;
charset=utf-8\"></head>");
sw.WriteLine("<body><ul>");

var dirs = Directory.GetDirectories(dirPath);


foreach (var d in dirs)
{
var link = d.Replace(rootPath, "").Replace('\\', '/');
sw.WriteLine("<li><a href=\"" + link + "\">" + Path.GetFileName(d) +
"</a></li>");
}

var files = Directory.GetFiles(dirPath);


foreach (var f in files)
{
var link = f.Replace(rootPath, "").Replace('\\', '/');
sw.WriteLine("<li><a href=\"" + link + "\">" + Path.GetFileName(f) +
"</a></li>");
}

sw.WriteLine("</ul></body></html>");
}
context.Response.OutputStream.Close();
}
private static void returnFile(HttpListenerContext context, string filePath)
{
context.Response.ContentType = getcontentType(Path.GetExtension(filePath));
var buffer = new byte[bufferSize];
using (var fs = File.OpenRead(filePath))
{
context.Response.ContentLength64 = fs.Length;
int read;
while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
context.Response.OutputStream.Write(buffer, 0, read);
}
context.Response.OutputStream.Close();
}
private static void return404(HttpListenerContext context)
{
context.Response.StatusCode = 404;
context.Response.Close();
}
private static string tuneUrl(string url)
{
url = url.Replace('/', '\\');
url = HttpUtility.UrlDecode(url, Encoding.UTF8);
url = url.Substring(1);
return url;
}
private static string getcontentType(string extension)
{
switch (extension)
{
case ".avi": return "video/x-msvideo";
case ".css": return "text/css";
case ".doc": return "application/msword";
case ".gif": return "image/gif";
case ".htm":
case ".html": return "text/html";
case ".jpg":
case ".jpeg": return "image/jpeg";
case ".js": return "application/x-javascript";
case ".mp3": return "audio/mpeg";
case ".png": return "image/png";
case ".pdf": return "application/pdf";
case ".ppt": return "application/vnd.ms-powerpoint";
case ".zip": return "application/zip";
case ".txt": return "text/plain";
default: return "application/octet-stream";
}
}
}

g. Să se realizeze un program pentru transferul fisierelor între două calculatoare,


având directoarele specificate.
Client
public class Client {
public static string currentMsg = "Idle";

public static void SendFile( string fileName


) { try {

Thread.Sleep( 5000 );
IPEndPoint ipEnd = CreateIPEndPoint( "10.163.142.181:5656" );
Socket clientSock = new Socket( AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP );
string filePath = "";

byte[] name_of_the_file = Encoding.ASCII.GetBytes( fileName );


byte[] fileNameLen =
BitConverter.GetBytes( name_of_the_file.Length ); byte[] fileData
= File.ReadAllBytes( filePath + fileName );
byte[] noBytesInMessage = BitConverter.GetBytes( fileData.Count() );
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
byte[] fileNameBytes = encoding.GetBytes( fileName );
clientSock.Connect( ipEnd );
clientSock.Send( fileNameLen );
clientSock.Send( name_of_the_file );
clientSock.Send( noBytesInMessage );
Console.WriteLine( "start sending file..." );
clientSock.Send( fileData );
Console.WriteLine( "File {0} was sent", fileName );
Console.WriteLine( "Disconnecting..." );
clientSock.Close();
Console.WriteLine( "File transferred." );
} catch (Exception ex) {
if (ex.Message == "No connection could be made")
currentMsg = "File Sending fail. Because server not
running."; else
currentMsg = "File Sending fail." + ex.Message;
}
}
public static IPEndPoint CreateIPEndPoint( string endPoint
) { string[] ep = endPoint.Split( ':' );
if (ep.Length < 2)
throw new FormatException( "Invalid endpoint
format" ); IPAddress ip;
if (ep.Length > 2) {
if (!IPAddress.TryParse( string.Join( ":", ep, 0, ep.Length - 1 ), out
ip )) { throw new FormatException( "Invalid ip-adress" );
}
} else {
if (!IPAddress.TryParse( ep[0], out ip )) {

throw new FormatException( "Invalid ip-adress" );

int port;

if (!int.TryParse( ep[ep.Length -

1], NumberStyles.None, NumberFormatInfo.CurrentInfo, out


port )) { throw new FormatException( "Invalid
port" );

return new IPEndPoint( ip, port );

}
Utilizarea clientului in programul principal:

static void Main( string[] args ) {

DirectoryInfo dir = new DirectoryInfo( @"C:\Napa\Inbox"


); List<string> file_names = new List<string>();

while (true) {
file_names.Clear();
file_names = DirSearch( @"C:\Napa\Inbox" );

//FileInfo[] files = dir.GetFiles();


//foreach (FileInfo file in files) {
foreach (string file in file_names) {
Console.WriteLine("Sending file {0}",
file); Client.SendFile( file );

}
}
}
static List<string> DirSearch( string sDir ) {
List<string> file_names = new
List<string>(); try {
foreach (string d in
Directory.GetDirectories( sDir )) { foreach
(string f in Directory.GetFiles( d )) {
file_names.Add( f );
}
DirSearch( d );
}
} catch (System.Exception excpt) {
Console.WriteLine( excpt.Message
);
}
return file_names;
}

Implementare Server

public class Server {


IPEndPoint ipEnd;
Socket sock;
TcpListener tcpListener;

public Server() {
IPAddress sIp = IPAddress.Parse(
"10.162.0.94" ); ipEnd = new IPEndPoint( sIp,
5656 ); tcpListener = new
TcpListener( 5656 );
sock = new Socket( AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP
);
sock.Bind( ipEnd );
}

public void StartServer() {


try {
Console.WriteLine( "Starting..." );
Console.WriteLine( "Running and waiting to receive
file." ); while (true) {
sock.Listen( 100 );
Socket clientSock = sock.Accept();
Console.WriteLine( "Client connected" );
byte[] fileNameLen = new byte[4];
int receivedBytesLen0 = clientSock.Receive( ( fileNameLen ) );
int no_of_bytes_in_filename = BitConverter.ToInt32( fileNameLen, 0
); byte[] name_of_the_file = new byte[no_of_bytes_in_filename];
int receivedBytesLen1 = clientSock.Receive( ( name_of_the_file ) );
string file_name =
System.Text.Encoding.ASCII.GetString( name_of_the_file
);

byte[] messageLen = new byte[4];


int receivedBytesLen2 = clientSock.Receive( ( messageLen ) );
int no_of_bytes_in_message = BitConverter.ToInt32( messageLen, 0 );

byte[] message_content = new byte[no_of_bytes_in_message];


int receivedBytesLen13= clientSock.Receive( ( message_content ) );

string fileName = "c:\\Napa\\Inbox\\Temp" +


file_name; try {
File.WriteAllBytes( @fileName, message_content );
} catch (Exception ex) {
}
//clientSock.Close();
Console.WriteLine( "Received & Saved file!" );
}
} catch (Exception ex) {
}
}
}

S-ar putea să vă placă și