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)
{

}
}
}

Leave a Reply