4. [3]

MyPacket.cs

CSocketPacket.cs

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

namespace MyPacket
{
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[100];
}
}

TcpSpecificPacket.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Sockets;

namespace MyPacket
{
public class TcpSpecificPacket
{
public TcpClient thisClient;
public byte[] dataBuffer = new byte[100];
}
}

4. [2]

Async Client

Designer

namespace MyAsyncClient
{
partial class MyAsyncClientForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtPort;
private System.Windows.Forms.Button cmdSend;
private System.Windows.Forms.TextBox textBoxArrived;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Button buttonConnect;
private System.Windows.Forms.Button buttonClose;
private System.Windows.Forms.TextBox textBoxSend;
private System.Windows.Forms.TextBox txtIPAddr;
private System.ComponentModel.IContainer components = null;

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support – do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.buttonClose = new System.Windows.Forms.Button();
this.buttonConnect = new System.Windows.Forms.Button();
this.txtPort = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.txtIPAddr = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.textBoxSend = new System.Windows.Forms.TextBox();
this.cmdSend = new System.Windows.Forms.Button();
this.textBoxArrived = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.labelStatus = new System.Windows.Forms.Label();
this.groupBox1.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox4.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.buttonClose);
this.groupBox1.Controls.Add(this.buttonConnect);
this.groupBox1.Controls.Add(this.txtPort);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.txtIPAddr);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(8, 8);
this.groupBox1.Name = “groupBox1″;
this.groupBox1.Size = new System.Drawing.Size(280, 77);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = “Settings”;
//
// buttonClose
//
this.buttonClose.Enabled = false;
this.buttonClose.Location = new System.Drawing.Point(160, 48);
this.buttonClose.Name = “buttonClose”;
this.buttonClose.Size = new System.Drawing.Size(96, 24);
this.buttonClose.TabIndex = 5;
this.buttonClose.Text = “Close”;
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
//
// buttonConnect
//
this.buttonConnect.Location = new System.Drawing.Point(160, 16);
this.buttonConnect.Name = “buttonConnect”;
this.buttonConnect.Size = new System.Drawing.Size(96, 24);
this.buttonConnect.TabIndex = 4;
this.buttonConnect.Text = “Connect”;
this.buttonConnect.Click += new System.EventHandler(this.cmdConnect_Click);
//
// txtPort
//
this.txtPort.Location = new System.Drawing.Point(72, 48);
this.txtPort.Name = “txtPort”;
this.txtPort.Size = new System.Drawing.Size(40, 20);
this.txtPort.TabIndex = 3;
this.txtPort.Text = “8000″;
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 48);
this.label2.Name = “label2″;
this.label2.Size = new System.Drawing.Size(32, 16);
this.label2.TabIndex = 2;
this.label2.Text = “Port:”;
//
// txtIPAddr
//
this.txtIPAddr.Location = new System.Drawing.Point(72, 24);
this.txtIPAddr.Name = “txtIPAddr”;
this.txtIPAddr.Size = new System.Drawing.Size(80, 20);
this.txtIPAddr.TabIndex = 1;
this.txtIPAddr.Text = “127.0.0.1″;
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 24);
this.label1.Name = “label1″;
this.label1.Size = new System.Drawing.Size(48, 16);
this.label1.TabIndex = 0;
this.label1.Text = “Host IP:”;
//
// textBoxSend
//
this.textBoxSend.Location = new System.Drawing.Point(16, 104);
this.textBoxSend.Multiline = true;
this.textBoxSend.Name = “textBoxSend”;
this.textBoxSend.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBoxSend.Size = new System.Drawing.Size(264, 82);
this.textBoxSend.TabIndex = 1;
//
// cmdSend
//
this.cmdSend.Location = new System.Drawing.Point(19, 104);
this.cmdSend.Name = “cmdSend”;
this.cmdSend.Size = new System.Drawing.Size(237, 24);
this.cmdSend.TabIndex = 2;
this.cmdSend.Text = “Send”;
this.cmdSend.Click += new System.EventHandler(this.buttonSend_Click);
//
// textBoxArrived
//
this.textBoxArrived.Location = new System.Drawing.Point(16, 244);
this.textBoxArrived.Multiline = true;
this.textBoxArrived.Name = “textBoxArrived”;
this.textBoxArrived.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBoxArrived.Size = new System.Drawing.Size(264, 72);
this.textBoxArrived.TabIndex = 3;
//
// groupBox2
//
this.groupBox2.Location = new System.Drawing.Point(8, 228);
this.groupBox2.Name = “groupBox2″;
this.groupBox2.Size = new System.Drawing.Size(280, 96);
this.groupBox2.TabIndex = 4;
this.groupBox2.TabStop = false;
this.groupBox2.Text = “Data Arrived”;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.cmdSend);
this.groupBox3.Location = new System.Drawing.Point(8, 88);
this.groupBox3.Name = “groupBox3″;
this.groupBox3.Size = new System.Drawing.Size(280, 134);
this.groupBox3.TabIndex = 5;
this.groupBox3.TabStop = false;
this.groupBox3.Text = “Send Data”;
//
// groupBox4
//
this.groupBox4.Controls.Add(this.labelStatus);
this.groupBox4.Location = new System.Drawing.Point(8, 330);
this.groupBox4.Name = “groupBox4″;
this.groupBox4.Size = new System.Drawing.Size(280, 42);
this.groupBox4.TabIndex = 6;
this.groupBox4.TabStop = false;
this.groupBox4.Text = “Status”;
//
// labelStatus
//
this.labelStatus.AutoSize = true;
this.labelStatus.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.labelStatus.Location = new System.Drawing.Point(5, 16);
this.labelStatus.Name = “labelStatus”;
this.labelStatus.Size = new System.Drawing.Size(99, 13);
this.labelStatus.TabIndex = 0;
this.labelStatus.Text = “Status messages …”;
//
// MyAsyncClientForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(294, 382);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.textBoxArrived);
this.Controls.Add(this.textBoxSend);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox3);
this.Name = “MyAsyncClientForm”;
this.Text = “MyAsyncClient”;
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();

}
/// <summary>
///
/// </summary>
/// <param name=”disposing”></param>
protected override void Dispose(bool disposing)
{

if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}

#endregion

private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.Label labelStatus;
}
}

Form.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using MyPacket;
using System.IO;

namespace MyAsyncClient
{
public partial class MyAsyncClientForm : Form
{
private delegate void CrossThreadCallsDelegate(string status);
private CrossThreadCallsDelegate crossThreadCall;
private CrossThreadCallsDelegate crossThreadCallForStatus;

public TcpClient tcpClient;

public MyAsyncClientForm()
{
InitializeComponent();
crossThreadCall = new CrossThreadCallsDelegate(WriteMessage);
crossThreadCallForStatus = new CrossThreadCallsDelegate(ReportStatus);
labelStatus.Text = “Client application started!”;
}

private void WriteMessage(string message)
{
textBoxArrived.Text += message + Environment.NewLine;
}

private void ReportStatus(string message)
{
labelStatus.Text = message + Environment.NewLine;
}

private void EnableCommands(bool abEnableConnect)
{
buttonClose.Enabled = !abEnableConnect;
buttonConnect.Enabled = abEnableConnect;
}

private void cmdConnect_Click(object sender, System.EventArgs e)
{

try
{
EnableCommands(true);
// get the remote IP address…
IPAddress ip = IPAddress.Parse(txtIPAddr.Text);
int iPortNo = int.Parse(txtPort.Text);
//create the end point
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
//create the socket instance…
tcpClient = new TcpClient();
//connect to the remote host…
tcpClient.Connect(ipEnd);
labelStatus.Invoke(crossThreadCallForStatus, new object[] { “Client connected to ” + ipEnd });
EnableCommands(false);
//watch for data ( asynchronously )…
WaitForData();
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
EnableCommands(true);
}
}
public void WaitForData()
{
try
{
TcpSpecificPacket theSocPkt = new TcpSpecificPacket();
theSocPkt.thisClient = tcpClient;
// now start to listen for any data…
theSocPkt.thisClient.GetStream().BeginRead(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, OnDataReceived, theSocPkt);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}

}

private void buttonSend_Click(object sender, System.EventArgs e)
{
try
{
byte[] byData = System.Text.Encoding.ASCII.GetBytes(textBoxSend.Text);
tcpClient.GetStream().Write(byData, 0, byData.Length);
textBoxSend.Text = “”;
labelStatus.Invoke(crossThreadCallForStatus, new object[] { “Sent ” + byData.Length + ” bytes of data.” });
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}

}

private void buttonClose_Click(object sender, System.EventArgs e)
{
if (tcpClient != null && tcpClient.Connected)
{
tcpClient.Close();
tcpClient = null;
EnableCommands(true);
}
}

public void OnDataReceived(IAsyncResult asyn)
{
try
{
TcpSpecificPacket theSockId = (TcpSpecificPacket)asyn.AsyncState;
int dataReceivedLength = theSockId.thisClient.GetStream().EndRead(asyn);
if (dataReceivedLength != 0)
{
textBoxArrived.Invoke(crossThreadCall, new object[] { Encoding.UTF8.GetString(theSockId.dataBuffer, 0, dataReceivedLength) });
//crossThreadCall(Encoding.UTF8.GetString(theSockId.dataBuffer, 0, dataReceivedLength));
labelStatus.Invoke(crossThreadCallForStatus, new object[] { “Received ” + dataReceivedLength + ” bytes of data from server.” });
WaitForData();
}
} catch (IOException)
{
labelStatus.Invoke(crossThreadCallForStatus, new object[] { “Server has been closed!” });
}
catch (ObjectDisposedException)
{
labelStatus.Invoke(crossThreadCallForStatus, new object[] { “Socket has been closed!” });
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
}
}

4. [1]

Async Server

Designer

namespace MyAsyncServer
{
partial class MyAsyncServerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.Windows.Forms.Label labelPort;
private System.Windows.Forms.TextBox txtPortNo;
private System.Windows.Forms.Button buttonListen;
private System.Windows.Forms.TextBox textBoxReceived;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.TextBox textBoxSend;
private System.Windows.Forms.Button buttonSend;
private System.ComponentModel.IContainer components = null;

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support – do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.buttonSet = new System.Windows.Forms.Button();
this.textBoxSet = new System.Windows.Forms.TextBox();
this.labelConn = new System.Windows.Forms.Label();
this.buttonListen = new System.Windows.Forms.Button();
this.txtPortNo = new System.Windows.Forms.TextBox();
this.labelPort = new System.Windows.Forms.Label();
this.textBoxReceived = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.buttonSend = new System.Windows.Forms.Button();
this.textBoxSend = new System.Windows.Forms.TextBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.labelStatus = new System.Windows.Forms.Label();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox4.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.buttonSet);
this.groupBox1.Controls.Add(this.textBoxSet);
this.groupBox1.Controls.Add(this.labelConn);
this.groupBox1.Controls.Add(this.buttonListen);
this.groupBox1.Controls.Add(this.txtPortNo);
this.groupBox1.Controls.Add(this.labelPort);
this.groupBox1.Location = new System.Drawing.Point(8, 16);
this.groupBox1.Name = “groupBox1″;
this.groupBox1.Size = new System.Drawing.Size(280, 75);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = “Settings”;
//
// buttonSet
//
this.buttonSet.Location = new System.Drawing.Point(144, 42);
this.buttonSet.Name = “buttonSet”;
this.buttonSet.Size = new System.Drawing.Size(104, 23);
this.buttonSet.TabIndex = 5;
this.buttonSet.Text = “Set”;
this.buttonSet.UseVisualStyleBackColor = true;
this.buttonSet.Click += new System.EventHandler(this.buttonSet_Click);
//
// textBoxSet
//
this.textBoxSet.Location = new System.Drawing.Point(89, 42);
this.textBoxSet.Name = “textBoxSet”;
this.textBoxSet.Size = new System.Drawing.Size(47, 20);
this.textBoxSet.TabIndex = 4;
this.textBoxSet.Text = “10″;
//
// labelConn
//
this.labelConn.AutoSize = true;
this.labelConn.Location = new System.Drawing.Point(16, 42);
this.labelConn.Name = “labelConn”;
this.labelConn.Size = new System.Drawing.Size(67, 13);
this.labelConn.TabIndex = 3;
this.labelConn.Text = “Client Count:”;
//
// buttonListen
//
this.buttonListen.Location = new System.Drawing.Point(144, 12);
this.buttonListen.Name = “buttonListen”;
this.buttonListen.Size = new System.Drawing.Size(104, 24);
this.buttonListen.TabIndex = 2;
this.buttonListen.Text = “Start Listening”;
this.buttonListen.Click += new System.EventHandler(this.buttonListen_Click);
//
// txtPortNo
//
this.txtPortNo.Location = new System.Drawing.Point(89, 16);
this.txtPortNo.Name = “txtPortNo”;
this.txtPortNo.Size = new System.Drawing.Size(47, 20);
this.txtPortNo.TabIndex = 1;
this.txtPortNo.Text = “8000″;
//
// labelPort
//
this.labelPort.Location = new System.Drawing.Point(16, 16);
this.labelPort.Name = “labelPort”;
this.labelPort.Size = new System.Drawing.Size(72, 16);
this.labelPort.TabIndex = 0;
this.labelPort.Text = “Port Number:”;
//
// textBoxReceived
//
this.textBoxReceived.Location = new System.Drawing.Point(14, 281);
this.textBoxReceived.Multiline = true;
this.textBoxReceived.Name = “textBoxReceived”;
this.textBoxReceived.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBoxReceived.Size = new System.Drawing.Size(266, 80);
this.textBoxReceived.TabIndex = 1;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.buttonSend);
this.groupBox2.Controls.Add(this.textBoxSend);
this.groupBox2.Location = new System.Drawing.Point(8, 97);
this.groupBox2.Name = “groupBox2″;
this.groupBox2.Size = new System.Drawing.Size(280, 155);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = “Send Data”;
//
// buttonSend
//
this.buttonSend.Location = new System.Drawing.Point(16, 120);
this.buttonSend.Name = “buttonSend”;
this.buttonSend.Size = new System.Drawing.Size(232, 24);
this.buttonSend.TabIndex = 1;
this.buttonSend.Text = “Send”;
this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);
//
// textBoxSend
//
this.textBoxSend.Cursor = System.Windows.Forms.Cursors.IBeam;
this.textBoxSend.Location = new System.Drawing.Point(8, 16);
this.textBoxSend.Multiline = true;
this.textBoxSend.Name = “textBoxSend”;
this.textBoxSend.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBoxSend.Size = new System.Drawing.Size(264, 96);
this.textBoxSend.TabIndex = 0;
//
// groupBox3
//
this.groupBox3.Location = new System.Drawing.Point(8, 258);
this.groupBox3.Name = “groupBox3″;
this.groupBox3.Size = new System.Drawing.Size(280, 112);
this.groupBox3.TabIndex = 3;
this.groupBox3.TabStop = false;
this.groupBox3.Text = “Data Received”;
//
// groupBox4
//
this.groupBox4.Controls.Add(this.labelStatus);
this.groupBox4.Location = new System.Drawing.Point(8, 378);
this.groupBox4.Name = “groupBox4″;
this.groupBox4.Size = new System.Drawing.Size(280, 38);
this.groupBox4.TabIndex = 4;
this.groupBox4.TabStop = false;
this.groupBox4.Text = “Satus”;
//
// labelStatus
//
this.labelStatus.AutoSize = true;
this.labelStatus.Font = new System.Drawing.Font(“Microsoft Sans Serif”, 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelStatus.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.labelStatus.Location = new System.Drawing.Point(6, 17);
this.labelStatus.Name = “labelStatus”;
this.labelStatus.Size = new System.Drawing.Size(99, 13);
this.labelStatus.TabIndex = 0;
this.labelStatus.Text = “Status messages …”;
//
// MyAsyncServerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(297, 428);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.textBoxReceived);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.groupBox3);
this.Name = “MyAsyncServerForm”;
this.Text = “MyAsyncServer”;
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MyAsyncServerForm_FormClosed);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();

}

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name=”disposing”>true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#endregion

private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.Label labelStatus;
private System.Windows.Forms.Button buttonSet;
private System.Windows.Forms.TextBox textBoxSet;
private System.Windows.Forms.Label labelConn;
}
}

Form.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.IO;
using MyPacket;

namespace MyAsyncServer
{
public partial class MyAsyncServerForm : Form
{
private delegate void CrossThreadCallsDelegate(string status);
private CrossThreadCallsDelegate crossThreadCall;
private CrossThreadCallsDelegate crossThreadCallForStatus;
private TcpListener tcpListener;
// numarul maxim de conexiui acceptate, avem nevoie de el pentru ca nu putem apela beginAccept la infinit.
private int clientCount = 0;

private List<TcpClient> clientList = new List<TcpClient>();

public MyAsyncServerForm()
{
InitializeComponent();
buttonListen.Enabled = false;
crossThreadCall = new CrossThreadCallsDelegate(WriteMessage);
crossThreadCallForStatus = new CrossThreadCallsDelegate(ReportStatus);
labelStatus.Text = “Application started!”;
}

private void WriteMessage(string message)
{
/*
ISynchronizeInvoke sync = this as ISynchronizeInvoke;
if (sync.InvokeRequired)
{
sync.Invoke(crossThreadCall, new object[] { message });
return;
}*/
textBoxReceived.Text += message + Environment.NewLine;
}

private void ReportStatus(string message)
{
labelStatus.Text = message + Environment.NewLine;
}

private void buttonListen_Click(object sender, EventArgs e)
{
try
{
//create the listening socket…
int portNo = int.Parse(txtPortNo.Text);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, portNo);
tcpListener = new TcpListener(ipLocal);
//start listening…
tcpListener.Start(10);
// create the call back for any client connections…
labelStatus.Invoke(crossThreadCallForStatus, new object[] { “Server waiting for client…” });
for (int i = 0; i < clientCount; i++)
{
tcpListener.BeginAcceptTcpClient(OnClientConnect, null);
}
buttonListen.Enabled = false;
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}

public void OnClientConnect(IAsyncResult asyn)
{
try
{
TcpClient tcpClient =  tcpListener.EndAcceptTcpClient(asyn);
clientList.Add(tcpClient);
labelStatus.Invoke(crossThreadCallForStatus, new object[] { “Client connected from ” + tcpClient.Client.RemoteEndPoint });
WaitForData(tcpClient);
}
catch (ObjectDisposedException)
{
MessageBox.Show(“OnClientConnection: Socket has been closed!”);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}

public void WaitForData(TcpClient tcpClient)
{
try
{
TcpSpecificPacket theSocPkt = new TcpSpecificPacket();
theSocPkt.thisClient = tcpClient;
theSocPkt.thisClient.GetStream().BeginRead(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, OnDataReceived, theSocPkt);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}

}

public void OnDataReceived(IAsyncResult asyn)
{
try
{
TcpSpecificPacket theSockId = (TcpSpecificPacket)asyn.AsyncState;

int dataReceivedLength = theSockId.thisClient.GetStream().EndRead(asyn);
if (dataReceivedLength != 0)
{
labelStatus.Invoke(crossThreadCallForStatus, new object[] { dataReceivedLength + ” bytes received from client: ” + theSockId.thisClient.Client.RemoteEndPoint });
textBoxReceived.Invoke(crossThreadCall, new object[] { Encoding.UTF8.GetString(theSockId.dataBuffer, 0, dataReceivedLength) });
WaitForData(theSockId.thisClient);
}
} catch(IOException) {
labelStatus.Invoke(crossThreadCallForStatus, new object[] { “Client has closed connection.” });
}
catch (ObjectDisposedException)
{
labelStatus.Invoke(crossThreadCallForStatus, new object[] { “Client socket has been closed.” });
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}

private void buttonSend_Click(object sender, System.EventArgs e)
{
try
{
byte[] byData = Encoding.UTF8.GetBytes(textBoxSend.Text);
foreach (TcpClient cl in clientList)
{
if (cl != null && cl.Connected) {
cl.GetStream().Write(byData, 0, byData.Length);
}
}

textBoxSend.Text = “”;
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}

private void buttonSet_Click(object sender, EventArgs e)
{
try
{
clientCount = int.Parse(textBoxSet.Text);
buttonListen.Enabled = true;
buttonSet.Enabled = false;
}
catch {
MessageBox.Show(“Format necorespunzator!”);
}
}

private void MyAsyncServerForm_FormClosed(object sender, FormClosedEventArgs e)
{
if (tcpListener != null)
{
// ma asigur ca inchid toate conexiunile
foreach (TcpClient cl in clientList)
{
cl.Close();
}
tcpListener.Stop();
}
}

private void MyAsyncServerForm_Load(object sender, EventArgs e)
{

}
}
}

Mutex

LockMutex.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace First
{
public class LockMutex
{
FileStream resource = null;

public LockMutex(String pathToFile)
{
resource = new FileStream(pathToFile, FileMode.Create, FileAccess.ReadWrite);
}

public void Read() {
//lock (resource) – am comentat liniile astea pentru a permite cititorilor accesul in paralel
// {
int thId = Thread.CurrentThread.ManagedThreadId;
resource.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(resource);
String s = sr.ReadToEnd();
Console.WriteLine(thId.ToString() + ” read : ” + s);
// }
}

public void Write() {
lock (resource)
{
int thId = Thread.CurrentThread.ManagedThreadId;
resource.Seek(0, SeekOrigin.End);
StreamWriter sw = new StreamWriter(resource);
String s = thId + ” :: ” + System.DateTime.Now.ToString();
sw.WriteLine(s);
Console.WriteLine(thId.ToString() + ” wrote : ” + s);
sw.Flush();
}
}

// am avut nevoie de metoda asta din cauza switch-ului, in momentul in care folosesc
// cealalta clasa ptr managementul resursei trebuie sa fiu sigura ca aceasta este disponibila
public void Close()
{
resource.Close();
}

/* destructor care asigura eliberarea resursei – nu e nevoie de el aici
~LockMutex() {
resource.Close();
}*/

}
}
MonitorMutex.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

namespace First
{
class MonitorMutex
{
static object synObj = new object();
FileStream resource = null;

public MonitorMutex(String pathToFile)
{
resource = new FileStream(pathToFile, FileMode.Create, FileAccess.ReadWrite);
}

public void Read()
{
// Monitor.Enter(synObj); – am comentat liniile astea pentru a permite cititorilor accesul in paralel
//  try
//  {
int thId = Thread.CurrentThread.ManagedThreadId;
resource.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(resource);
String s = sr.ReadToEnd();
Console.WriteLine(thId.ToString() + ” read : ” + s);
//  }
//  catch (Exception e){
//     Console.WriteLine(e.Message);
// }
//      Monitor.Exit(synObj);

}

public void Write()
{
Monitor.Enter(synObj);
try
{
int thId = Thread.CurrentThread.ManagedThreadId;
resource.Seek(0, SeekOrigin.End);
StreamWriter sw = new StreamWriter(resource);
String s = thId + ” :: ” + System.DateTime.Now.ToString();
sw.WriteLine(s);
Console.WriteLine(thId.ToString() + ” wrote : ” + s);
sw.Flush();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Monitor.Exit(synObj);
}

// am avut nevoie de metoda asta din cauza switch-ului, in momentul in care folosesc
// cealalta clasa ptr managementul resursei trebuie sa fiu sigura ca aceasta este disponibila
public void Close() {
resource.Close();
}

/*destructor care asigura eliberarea resursei – nu e nevoie de el aici
~MonitorMutex() {
resource.Close();
}*/
}
}
MutexMutex.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace First
{
class MutexMutex
{
FileStream resource = null;
public Mutex fileMutex;

public MutexMutex(String pathToFile)
{
resource = new FileStream(pathToFile, FileMode.Create, FileAccess.ReadWrite);
fileMutex = new Mutex();
}

public void Read()
{
//fileMutex.WaitOne(); – am comentat liniile astea pentru a permite cititorilor accesul in paralel
//try
//{
int thId = Thread.CurrentThread.ManagedThreadId;
resource.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(resource);
String s = sr.ReadToEnd();
Console.WriteLine(thId.ToString() + ” read : ” + s);
//} catch (Exception e) {
//   Console.WriteLine(“Exception happened: ” + e.Message);
// }
// fileMutex.ReleaseMutex();
}

public void Write()
{
fileMutex.WaitOne();
try {
int thId = Thread.CurrentThread.ManagedThreadId;
resource.Seek(0, SeekOrigin.End);
StreamWriter sw = new StreamWriter(resource);
String s = thId + ” :: ” + System.DateTime.Now.ToString();
sw.WriteLine(s);
Console.WriteLine(thId.ToString() + ” wrote : ” + s);
sw.Flush();
} catch (Exception e) {
Console.WriteLine(“Exception happened: ” + e.Message);
}
fileMutex.ReleaseMutex();
}

// am avut nevoie de metoda asta din cauza switch-ului, in momentul in care folosesc
// cealalta clasa ptr managementul resursei trebuie sa fiu sigura ca aceasta este disponibila
public void Close() {
fileMutex.Close();
resource.Close();
}

/*destructor care asigura eliberarea resursei – nu e nevoie de el aici
~MutexMutex() {
fileMutex.Close();
resource.Close();
}*/
}
}
Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace First
{
class Program
{
// metoda  ce poae fi folosita pentru a vehicula date de dimensiuni mari
public static String getSring(int id) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 2000; i++)
sb.AppendLine(id + “wrote: ” + System.DateTime.Now);
return sb.ToString();
}

static void Main(string[] args)
{
//s-a dat accesul cititorilorx in paralel la resursa
Thread[] ta = new Thread[10];
LockMutex mx = null;
MonitorMutex mm = null;
MutexMutex mxmx = null;
SemaphoreMutex sm = null;
ReaderWriterLockMutex rwm = null;
mx = new LockMutex(“test.txt”);
Thread firstWriter = new Thread(mx.Write);
firstWriter.Start();
firstWriter.Join();
for (int i = 0; i < 10; ++i)
{
int opt = new Random().Next(2);
ta[i] = opt == 0 ? new Thread(mx.Read) : new Thread(mx.Write);
ta[i].Start();
}
Console.WriteLine(“\n>>> Press any key to finish lock example and release resources…<<<”);
Console.ReadKey();
Console.WriteLine(“————————————————————”);
mx.Close();

mm = new MonitorMutex(“test.txt”);
firstWriter = new Thread(mm.Write);
firstWriter.Start();
firstWriter.Join();
for (int i = 0; i < 10; ++i)
{
int opt = new Random().Next(2);
ta[i] = opt == 0 ? new Thread(mm.Read) : new Thread(mm.Write);
ta[i].Start();
}
Console.WriteLine(“\n>>> Press any key to finish Monitor example and release resources…<<<”);
Console.ReadKey();
Console.WriteLine(“————————————————————”);
mm.Close();

mxmx = new MutexMutex(“test.txt”);
firstWriter = new Thread(mxmx.Write);
firstWriter.Start();
firstWriter.Join();
for (int i = 0; i < 10; ++i)
{
int opt = new Random().Next(2);
ta[i] = opt == 0 ? new Thread(mxmx.Read) : new Thread(mxmx.Write);
ta[i].Start();
}
Console.WriteLine(“\n>>> Press any key to finish Mutex example and release resources…<<<”);
Console.ReadKey();
Console.WriteLine(“————————————————————”);
mxmx.Close();

sm = new SemaphoreMutex(“test.txt”);
firstWriter = new Thread(sm.Write);
firstWriter.Start();
firstWriter.Join();
for (int i = 0; i < 10; ++i)
{
int opt = new Random().Next(2);
ta[i] = opt == 0 ? new Thread(sm.Read) : new Thread(sm.Write);
ta[i].Start();
}
Console.WriteLine(“\n>>> Press any key to finish Semaphore example and release resources…<<<”);
Console.ReadKey();
Console.WriteLine(“————————————————————”);
sm.Close();

rwm = new ReaderWriterLockMutex(“test.txt”);
firstWriter = new Thread(new ParameterizedThreadStart(rwm.Write));
firstWriter.Start(ReaderWriterLockMutex.writerTimeouts);
firstWriter.Join();
for (int i = 0; i < 10; ++i)
{
int opt = new Random().Next(2);
if (opt == 0)
{
ta[i] = new Thread(new ParameterizedThreadStart(rwm.Read));
ta[i].Start(ReaderWriterLockMutex.readerTimeouts);
}
else {
ta[i] = new Thread(new ParameterizedThreadStart(rwm.Write));
ta[i].Start(ReaderWriterLockMutex.writerTimeouts);
}
}
Console.WriteLine(“\n>>> Press any key to finish ReaderWriterLock example and release resources…<<<”);
Console.ReadKey();
Console.WriteLine(“————————————————————”);
rwm.Close();

Console.WriteLine(“\n>>> Press any key to exit…<<<”);
Console.ReadKey();
}
}
}
ReaderWriterLockMutex.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace First
{
class ReaderWriterLockMutex
{
FileStream resource = null;
ReaderWriterLock readerWriterLock = null;
public static int readerTimeouts = 0;
public static int writerTimeouts = 0;
int reads = 0;
int writes = 0;

public ReaderWriterLockMutex(String pathToFile)
{
resource = new FileStream(pathToFile, FileMode.Create, FileAccess.ReadWrite);
readerWriterLock  = new ReaderWriterLock();
}

public void Read(object obj)
{
int timeOut = (int)obj;
try
{
readerWriterLock.AcquireReaderLock(timeOut);
try
{
int thId = Thread.CurrentThread.ManagedThreadId;
resource.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(resource);
String s = sr.ReadToEnd();
Console.WriteLine(thId.ToString() + ” read : ” + s);
Interlocked.Increment(ref reads);
}
finally
{
readerWriterLock.ReleaseReaderLock();
}
}
catch (ApplicationException)
{
Interlocked.Increment(ref  readerTimeouts);
}
}

public void Write(object obj)
{
int timeOut = (int)obj;
try
{
readerWriterLock.AcquireWriterLock(timeOut);
try
{
int thId = Thread.CurrentThread.ManagedThreadId;
resource.Seek(0, SeekOrigin.End);
StreamWriter sw = new StreamWriter(resource);
String s = thId + ” :: ” + System.DateTime.Now.ToString();
sw.WriteLine(s);
Console.WriteLine(thId.ToString() + ” wrote : ” + s);
sw.Flush();
Interlocked.Increment(ref  writes);
}
finally
{
readerWriterLock.ReleaseWriterLock();
}
}
catch (ApplicationException)
{
Interlocked.Increment(ref writerTimeouts);
}
}

// am avut nevoie de metoda asta din cauza switch-ului, in momentul in care folosesc
// cealalta clasa ptr managementul resursei trebuie sa fiu sigura ca aceasta este disponibila
public void Close()
{
resource.Close();
}

/*destructor care asigura eliberarea resursei – nu e nevoie de el aici
~ReaderWriterLockMutex() {
resource.Close();
}*/

}
}
SemaphoreMutex.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace First
{
class SemaphoreMutex
{
FileStream resource = null;
Semaphore semaphore = null;

public SemaphoreMutex(String pathToFile)
{
resource = new FileStream(pathToFile, FileMode.Create, FileAccess.ReadWrite);
semaphore = new Semaphore(10, 10);
}

public void Read()
{
//semaphore.WaitOne(); – am comentat liniile astea pentru a permite cititorilor accesul in paralel
//try
// {
int thId = Thread.CurrentThread.ManagedThreadId;
resource.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(resource);
String s = sr.ReadToEnd();
Console.WriteLine(thId.ToString() + ” read : ” + s);
// } catch (Exception e) {
//   Console.WriteLine(“Exception happened: ” + e.Message);
//}
//semaphore.Release();
}

public void Write()
{
semaphore.WaitOne();
try
{
int thId = Thread.CurrentThread.ManagedThreadId;
resource.Seek(0, SeekOrigin.End);
StreamWriter sw = new StreamWriter(resource);
String s = thId + ” :: ” + System.DateTime.Now.ToString();
sw.WriteLine(s);
Console.WriteLine(thId.ToString() + ” wrote : ” + s);
sw.Flush();
}
catch (Exception e)
{
Console.WriteLine(“Exception happened: ” + e.Message);
}
semaphore.Release();
}

// am avut nevoie de metoda asta din cauza switch-ului, in momentul in care folosesc
// cealalta clasa ptr managementul resursei trebuie sa fiu sigura ca aceasta este disponibila
public void Close()
{
semaphore.Close();
resource.Close();
}

/*destructor care asigura eliberarea resursei – nu e nevoie de el aici
~SemaphoreMutex() {
semaphore.Close();
resource.Close();
}*/
}
}

Reader/Writer

3 projects: Main project, Reader, Writer.

MainProject, Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace MainProject
{
class Program
{
static void Main(string[] args)
{
FileStream fs = new FileStream(“test.txt”, FileMode.Create);
fs.Close();

Console.WriteLine(“Current context :” + AppDomain.CurrentDomain.Id);

AppDomain dw = AppDomain.CreateDomain(“Writers domain”);
AppDomain dr = AppDomain.CreateDomain(“Readers domain”);

for (int i = 0; i < 20; i++)
{
int opt = new Random().Next(2);
if (opt == 0)
{
dw.ExecuteAssembly(@”..\..\..\Reader\bin\Debug\Reader.exe”);
}
else {
dr.ExecuteAssembly(@”..\..\..\Writer\bin\Debug\Writer.exe”);
}
}

Console.WriteLine(“>>> Press any key to exit… <<<”);
Console.ReadKey();
}
}
}

Reader, Reader.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

namespace Reader
{
class Reader
{
static Mutex localMutex = null;
const string mutexName = “LocalMutex”;
static string path = @”..\..\..\MainProject\bin\Debug\test.txt”;

static void Main(string[] args)
{
//Create the mutex****************************************
try
{
localMutex = Mutex.OpenExisting(mutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
Console.WriteLine(“Mutex is Null!”);
}
if (localMutex == null)
{
localMutex = new Mutex(false, mutexName);
}

new Thread(ReadFromFile).Start();
}

static void ReadFromFile()
{
if (localMutex.WaitOne(100000, false))
{
StreamReader sr = null;
try
{
sr = new StreamReader(path);
sr.BaseStream.Seek(0, SeekOrigin.Begin);
Console.WriteLine(“domain no.:” + AppDomain.CurrentDomain.Id + “, Thread:” + Thread.CurrentThread.ManagedThreadId + ” read: ” + sr.ReadToEnd() );
Thread.Sleep(200); // delay necesar observarii apelurilor in paralel
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
finally
{
sr.Close();
localMutex.ReleaseMutex();
}
}
}
}
}

Writer, Writer.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

namespace Writer
{
class Writer
{
static Mutex localMutex;
const string MutexName = “LocalMutex”;
static string path = @”..\..\..\MainProject\bin\Debug\test.txt”;

static void Main(string[] args)
{
localMutex = null;
try
{
localMutex = Mutex.OpenExisting(MutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
Console.WriteLine(“Mutex is Null!”);
}
if (localMutex == null)
{
localMutex = new Mutex(false, MutexName);
}

new Thread(WriteToFile).Start();
}

static void WriteToFile()
{
if (localMutex.WaitOne(100000, false))
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(path,true);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(“domain no.:” + AppDomain.CurrentDomain.Id + “, thread ” + Thread.CurrentThread.ManagedThreadId + ” :: ” + System.DateTime.Now.ToString());
Console.WriteLine(“domain no.:” + AppDomain.CurrentDomain.Id + “, thread ” + Thread.CurrentThread.ManagedThreadId + ” wrote. ” );
Thread.Sleep(200); // delay necesar observarii apelurilor in paralel
sw.Flush();
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
finally
{
sw.Close();
localMutex.ReleaseMutex();
}
}
}
}
}

Network Information Part 2.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.NetworkInformation;
using System.Xml;

namespace NetworkInformation
{
class Program
{
static void Main(string[] args)
{
IPGlobalProperties props     = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] interfete = NetworkInterface.GetAllNetworkInterfaces();

//creez fisier XML
XmlTextWriter textWriter = new XmlTextWriter(@”C:\Documents and Settings\admin\Desktop\SD\networkInfo.xml”, null);

//deschid pentru a scrie
textWriter.WriteStartDocument();

//scriu un comentariu in fisierul XML
textWriter.WriteComment(“Interfete retea pentru ” + props.HostName);

//primul element
textWriter.WriteStartElement(“host”);

foreach (NetworkInterface interfata in interfete)
{
IPInterfaceProperties ipprop = interfata.GetIPProperties();

//begin interface
textWriter.WriteStartElement(“interface”);

//attribute
textWriter.WriteAttributeString(“name”, interfata.Name);

textWriter.WriteStartElement(“description”);
textWriter.WriteString(interfata.Description);
textWriter.WriteEndElement();

textWriter.WriteStartElement(“type”);
textWriter.WriteString(interfata.NetworkInterfaceType.ToString());
textWriter.WriteEndElement();

if (interfata.NetworkInterfaceType == NetworkInterfaceType.Loopback)
continue;

textWriter.WriteStartElement(“viteza”);
textWriter.WriteString(interfata.Speed + “bps”);
textWriter.WriteEndElement();

textWriter.WriteStartElement(“stare”);
textWriter.WriteString(interfata.OperationalStatus.ToString());
textWriter.WriteEndElement();

textWriter.WriteStartElement(“adresaFizica”);
textWriter.WriteString(interfata.GetPhysicalAddress().ToString());
textWriter.WriteEndElement();

textWriter.WriteStartElement(“sufixDNS”);
textWriter.WriteString(ipprop.DnsSuffix);
textWriter.WriteEndElement();

textWriter.WriteStartElement(“adreseIP”);
UnicastIPAddressInformationCollection adreseIP = ipprop.UnicastAddresses;
if (adreseIP.Count > 0)
{
foreach (UnicastIPAddressInformation uni in adreseIP)
{
textWriter.WriteAttributeString(“adresaIPunicast”,uni.Address.ToString());

textWriter.WriteStartElement(“Mask”);
textWriter.WriteString(uni.IPv4Mask.ToString());
textWriter.WriteEndElement();

/*Console.WriteLine((DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime)).ToString());
Console.Read();
*/

/*
textWriter.WriteStartElement(“DHCP lease time”);
textWriter.WriteString((DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime)).ToString());
textWriter.WriteEndElement();*/
}
}
textWriter.WriteEndElement();

//end interface
textWriter.WriteEndElement();
}
textWriter.WriteEndElement();

// end the document.
textWriter.WriteEndDocument();

// close writer
textWriter.Close();

}
}
}

Ex3.

Careful

Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace Pr2
{
class Program
{

public delegate void threadDelegate(string message);

static public event threadDelegate unEvent;
static void Main(string[] args)
{
bool dirValid = false;
string path = “”;
string responsePrompt=”";
while (!dirValid && path != “q”)
{
Console.WriteLine(“\nIntroduceti calea spre director (sau q pentru a iesi din bucla): “);
path = Console.ReadLine();
dirValid = dirExists(path);
if (dirValid && dirIsEmpty(path))
{
Console.WriteLine(“\nDirectorul a fost gasit dar este gol, generez fisiere.”);
generator_de_fisiere(path);
}
}
if (dirValid)
Console.WriteLine(“\nDirectorul ” + path + ” a fost gasit.”);
else
{
//s-a introdus q
return;
}
responsePrompt = “”;
while (responsePrompt != “n” && responsePrompt != “N” && responsePrompt != “y” && responsePrompt != “Y”)
{
Console.WriteLine(“\nDoriti sa stergeti continutul fiserului ” + path + ” ? (y/n)”);
responsePrompt = Console.ReadLine();
}
if (responsePrompt == “Y” || responsePrompt == “y”)
{
//stergere
stergere(path);
}
Console.WriteLine(“\t\tApasati orice tasta pentru a termina executia programului.”);
Console.ReadKey();
}

static bool dirExists(string path)
{
return Directory.Exists(path);
}

static bool dirIsEmpty(string path)
{
string[] fisiere = Directory.GetFiles(path);
string[] directoare = Directory.GetDirectories(path);
/*foreach (string s in fisiere)
{
Console.WriteLine(s);
}
foreach (string s in directoare)
{
Console.WriteLine(s);
}*/
if (fisiere.Length > 0 || directoare.Length > 0)
return false;
else
return true;
}

static void stergere(string path)
{
if (!dirExists(path))
{
Console.WriteLine(“Directorul nu exista.”);
return;
}
if (dirIsEmpty(path))
{
Console.WriteLine(“Directorul “+path+” este gol.”);
return;
}
//
string[] fisiere = Directory.GetFiles(path);
//stergere fisere
Thread[] threads = new Thread[fisiere.Length];
//event
unEvent += new threadDelegate(afisare_mesaj);
for (int i = 0; i < fisiere.Length; i++)
{
threads[i] = new Thread(sterge_fisier);
threads[i].Start(fisiere[i]);
//Thread.Sleep(500);
}
//reapel pt stergere directoare
string[] directoare = Directory.GetDirectories(path);
foreach (string dir in directoare)
{
stergere(dir);
Thread thDir = new Thread(stergere_director);
thDir.Start(dir);
}
}

static void sterge_fisier(object path)
{
//stergerea logica
stergere_logica(path as string);
unEvent.Invoke(“a fost sters logic “+path);
//stergerea fizica
stergere_fizica(path as string);
}

static void stergere_logica(string path)
{
byte[] bytes = File.ReadAllBytes(path);
for (int i = 0; i < bytes.Length; i++)
bytes[i] = 0;
File.WriteAllBytes(path, bytes);

}

static void stergere_fizica(string path)
{
File.Delete(path);
}

static void afisare_mesaj(string message)
{
Console.WriteLine(“[{0}] – {1}.”,Thread.CurrentThread.ManagedThreadId,message);
}

static void generator_de_fisiere(string path)
{
for (int i=0; i<600; i++)
{
StringBuilder sb = new StringBuilder();
sb.Append(path);
sb.Append(“/”);
sb.Append(i);
sb.Append(“fis.txt”);
//
FileStream fs = File.Open(sb.ToString(), FileMode.OpenOrCreate, FileAccess.ReadWrite);

byte[] bytes = new byte[300];
for (int j = 0; j < 300; j++)
bytes[j] = (byte) j;
fs.Write(bytes, 0, 300);
}
}

static void stergere_director(object path)
{
while (Directory.GetFiles(path as string).Length != 0)
{
Thread.Sleep(100);
}
Directory.Delete(path as string);
}

}
}

Description

500 si 1000

File comparation

Carefull

Program.cs, Differ.cs

Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Xml.Serialization;

namespace p1exam
{
class Program
{
static string path1 = “f1.txt”;
static string path2 = “f2.txt”;
static int size = 0;
static int random = 0;
static int cat = 0;
static int rest = 0;
static List<Differ> colectie = new List<Differ>();
static Differ diferit = null;
static   FileStream f1 ;
static    FileStream f2;
static object obj = new object();

internal   class douaValori
{
public  int poz0;
public  int poz1;

}
public  static void comparare(object interv)
{
douaValori poz = (douaValori)interv;

int[] p=new int[2];
p[0]=poz.poz0;
p[1]=poz.poz1;

lock (obj)
{
Console.WriteLine(“Pozitii in apel:” +p[0] + ” to ” + p[1]);

f1.Seek((long)p[0], SeekOrigin.Begin);
f2.Seek((long)p[0], SeekOrigin.Begin);

byte[] buff1 = new byte[p[1] – p[0] + 1];
byte[] buff2 = new byte[p[1] – p[0] + 1];

f1.Read(buff1, 0, p[1] – p[0]);
f2.Read(buff2, 0, p[1] – p[0]);

for (int i = 0; i < buff1.Length; i++)
{
if (buff1[i] != buff2[i])
{
diferit = new Differ();
diferit.Pozitie = i;
diferit.Bit_diferit = buff1[i];

lock (colectie)
{
colectie.Add(diferit);
}
}
}

}

}

static void Main(string[] args)
{

f1 = new FileStream(path1, FileMode.Open, FileAccess.Read);
f2 = new FileStream(path2, FileMode.Open, FileAccess.Read);

if (f1.Length == f2.Length)
{
Console.WriteLine(“Sunt egale ca dimensiune!!!”);
size = (int)f1.Length;
Random r = new Random();
random = r.Next(0, size);
if (size % random != 0)
{
int[] poz = new int[2];
int i=0;
cat = (int)(size / random);
rest = size – (random * cat);
Thread[] threads = new Thread[cat + 1];
douaValori pozz = null;
poz[0] = 0;
for (i = 0; i < cat; i++)
{
if (i != 0)
poz[0] = poz[0] + random + 1;
poz[1] = poz[1] + random;
pozz = new douaValori();
pozz.poz0 = poz[0];
pozz.poz1 = poz[1];
Console.WriteLine(“Pozitii inainte de apel:” + poz[0] + ” to ” + poz[1]);
threads[i] = new Thread(new ParameterizedThreadStart(comparare));
threads[i].Start(pozz);
}

//restul
poz[0] = poz[1] + 1;
poz[1] = poz[1] + rest;
pozz = new douaValori();
pozz.poz0 = poz[0];
pozz.poz1 = poz[1];
threads[i] = new Thread(new ParameterizedThreadStart(comparare));
threads[i].Start(pozz);

for (int j = 0; j < (cat+1); j++)
threads[j].Join();

XmlSerializer x = new XmlSerializer(typeof(List<Differ>));
TextWriter w = new StreamWriter(“list.xml”);
x.Serialize(w, colectie);
w.Close();

}

}
else
Console.WriteLine(“Nu sunt egale ca dimensiune!!!”);
f1.Close();
f2.Close();
Console.ReadKey();
}
}
}

Differ.cs

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

namespace p1exam
{
public class Differ
{
private int pozitie;

public int Pozitie
{
get { return pozitie; }
set { pozitie = value; }
}
private byte bit_diferit;

public byte Bit_diferit
{
get { return bit_diferit; }
set { bit_diferit = value; }
}

public Differ()
{ }
}
}

Web application example

Default.aspx

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Procesare String</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div style=”border:solid 1px #ccc;padding:10px;width:500px;height:500px;position:relative; background-color:#eee”>
<!– String Label –>
<asp:Label ID=”labelString” runat=”server” Style=”z-index:102;font-family:Arial; font-size:small;” Text=”String:”></asp:Label>
<br />

<!– Text Input –>
<asp:TextBox ID=”textBox” runat=”server” Style=”z-index:105;font-family:Arial; font-size:small;” Width=”256px”></asp:TextBox>

<!– Validare Text Input–>
<asp:CustomValidator ID=”ValidateText” runat=”server” ControlToValidate=”textBox” ErrorMessage=”Nu este text!” OnServerValidate=”ValidateText_ServerValidate” Style=”z-index:108;”>
</asp:CustomValidator>
<br /><br />

<!– Tip Procesare –>
<asp:Label ID=”labelTipProcesare” runat=”server” Style=”z-index:104;font-family:Arial; font-size:small;” Text=”Tip Procesare”></asp:Label>
<br />
<!– DropDown List –>
<asp:DropDownList ID=”dropDownList” runat=”server” Style=”z-index: 109;font-family:Arial; font-size:small;” Width=”256px”>
<asp:ListItem Value=”0″>Litere mici</asp:ListItem>
<asp:ListItem Value=”1″>Litere mari</asp:ListItem>
<asp:ListItem Value=”2″>Valoare numerica</asp:ListItem>
</asp:DropDownList>

<!– Nr. Prim –>
<asp:Label ID=”labelNrPrim” runat=”server” Style=”z-index: 103;font-family:Arial; font-size:small;” Text=”Nr.Prim:”></asp:Label>
<!– Nr. Prim Input –>
<asp:TextBox ID=”nrBox” runat=”server” Style=”z-index:106;font-family:Arial; font-size:small;” Width=”118px”></asp:TextBox>

<!– Validare Nr. Prim –>
<asp:CustomValidator ID=”ValidateNrPrim” runat=”server” ControlToValidate=”nrBox” ErrorMessage=”Nu este nr. prim!” OnServerValidate=”ValidateNrPrim_ServerValidate” Style=”z-index:107;”>
</asp:CustomValidator><br /><br />

<!– Proceseaza –>
<asp:Button ID=”butonProceseaza” runat=”server” Style=”z-index:100;font-family:Arial; font-size:small;” Text=”Proceseaza” Width=”107px” OnClick=”Proceseaza_Click” />
<br /><br />
<!– ListBox cu Select –>
<asp:ListBox ID=”listBox” runat=”server” Height=”135px” SelectionMode=”Multiple” Style=”z-index:110;” Width=”300px”>
</asp:ListBox>
<br /><br />
<!– Sterge –>
<asp:Button ID=”buttonSterge” runat=”server” Style=”z-index:111;font-family:Arial; font-size:small;” Text=”Sterge” Width=”107px” OnClick=”Sterge_Click” />
</div>
</form>
</body>
</html>

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.UI.MobileControls;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void ValidateNrPrim_ServerValidate(object source, ServerValidateEventArgs args)
{
int nr = Int32.Parse(nrBox.Text);
args.IsValid = true;
for(int i=2;i<=nr/2;i++)
if (nr % i == 0)
{
args.IsValid = false;
break;
}
}

protected void ValidateText_ServerValidate(object source, ServerValidateEventArgs args)
{
/*double nr;
string text = textBox.Text.Trim();
bool b = double.TryParse(text, out nr);
if (b)
args.IsValid = false;
else
args.IsValid = true;
*/
string text  = textBox.Text.Trim();
args.IsValid = true;
for (int i = 0; i < text.Length; i++)
if (char.IsDigit(text[i]) == true)
args.IsValid = false;
}

protected void Proceseaza_Click(object sender, EventArgs e)
{
switch (dropDownList.SelectedValue)
{
case “0″:
listBox.Items.Add(textBox.Text.ToLower());
break;
case “1″:
listBox.Items.Add(textBox.Text.ToUpper());
break;
case “2″:
int prim = Int32.Parse(nrBox.Text);
string s = textBox.Text;
int rez=0;
for (int i=0;i<s.Length – 1;i++)
rez = prim *((int)s[i])+(int)s[i+1];
listBox.Items.Add(rez.ToString());
break;
}
}
protected void Sterge_Click(object sender, EventArgs e)
{
ListItemCollection collection = new ListItemCollection();
foreach (ListItem item in listBox.Items)
{
if (item.Selected)
collection.Add(item);
}
foreach (ListItem item in collection)
{
listBox.Items.Remove(item);
}
}
}

Multiple Threads

Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

namespace l3p1
{
class Program
{
public const int NUM_THREADS = 10;
static FileStream myFile = new FileStream(@”E:\1311\lab3\l3p1\l3p1\f.txt”, FileMode.Open,
FileAccess.Read);
static StreamReader fileRead = new StreamReader(myFile);
static void Main(string[] args)
{
List<Thread> readThreads = new List<Thread>();
for (int i = 0; i < NUM_THREADS; i++)
{
Reader rd = new Reader(myFile);
Thread myThread = new Thread(rd.DoWork);
myThread.Name = i.ToString();
readThreads.Add(myThread);
}
foreach (Thread t in readThreads)
{
t.Start();
}
Console.ReadLine();
}

static void readFile()
{
while (!fileRead.EndOfStream)
{
string line = fileRead.ReadLine();
System.Console.WriteLine(“Thread-ul {0} a citit:{1}”, Thread.CurrentThread.Name, line);
Thread.Sleep(30);
}
}
}
}

Reader.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

namespace l3p1
{
class Reader
{
FileStream _file;

public Reader(FileStream file)
{
_file = file;
}

public void DoWork()
{
while (true)
{
StreamReader myStrRead = new StreamReader(_file);
while (myStrRead.EndOfStream)
{
Thread.Sleep(20);
}
string line = myStrRead.ReadLine();
_file.Seek(0, SeekOrigin.Begin);
Console.WriteLine(“{0}(r):{1}”, Thread.CurrentThread.Name, line);
Thread.Sleep(30);
}
}
}
}

Follow

Get every new post delivered to your Inbox.