PDA

View Full Version : سوال: socket programing



mahbobeh63
چهارشنبه 15 آذر 1391, 15:25 عصر
using System;
using System.Collections.Generic;

using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;

namespace Client
{
class ClientManager
{

Socket clientRemote;//clientRemote az noe socket tarif shode ast
byte[] Buffer;// ye buffer mikhastim
AsyncCallback asyncCallBack;//baraye asyncron kardan be kar mire
FrmClient frmClient;
public ClientManager(FrmClient frm)
{


this.clientRemote = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//ye socket baz mikonim
this.Buffer = new byte[10000];
this.frmClient = frm;

}
public void Connet(string IpTarget, int PortNumber)
{
try// agar connect shod ke hich
{
IPEndPoint endRemote = new IPEndPoint(IPAddress.Parse(IpTarget), PortNumber);
this.clientRemote.Connect(endRemote);



WaitForData(); //dare goosh mide be khat ke aya coonect shodim ya na ?!
frmClient.GetStatues("ارتباط برقرار است");
}
catch // agar nashod 2ye catch mgim ke connect nashodi!
{
System.Windows.Forms.MessageBox.Show("لطفا سرور را راه اندازی کنید و مجدا ارتباط برقرار کنید");
frmClient.GetStatues("ارتباط برقرار نیست");
}
}
private void WaitForData()
{
try
{
if (this.asyncCallBack == null)
this.asyncCallBack = new AsyncCallback(OnResivetData);// inja new kardim pas ba'den new nemikonim dge (3khat paaeen tar!)
PacketClient packClient = new PacketClient(this.clientRemote);
packClient.BufferClient = new byte[packClient.RemoteClient.SendBufferSize]; //buffer ra por mikonad
packClient.RemoteClient.BeginReceive(packClient.Bu fferClient, 0, packClient.BufferClient.Length, SocketFlags.None, OnResivetData, packClient);
}
catch
{

}

}
private void OnResivetData(IAsyncResult async) // baraye inke har dafe ehtiaj be coonect shodan nbashe va dar vaghe be
//in khater ke nemikhaym modam listen konim tabe'e wait 4 data ra 2bare inja seda zadim
{
try
{
PacketClient packClient = async.AsyncState as PacketClient;
int iRx = packClient.RemoteClient.EndReceive(async);
frmClient.GetResult(packClient.BufferClient);
WaitForData();
}
catch { }
}
public void Send(string Msg) // baraye send
{
try
{
PacketClient packClient = new PacketClient(this.clientRemote );
packClient.BufferClient =UnicodeEncoding.UTF8.GetBytes(Msg);
packClient.RemoteClient.BeginSend(packClient.Buffe rClient, 0, packClient.BufferClient.Length, SocketFlags.None, new AsyncCallback(OnSend), packClient);
}
catch
{

}
}
private void OnSend(IAsyncResult async)
{
PacketClient packClient = async.AsyncState as PacketClient;
int iRx = packClient.RemoteClient.EndSendTo(async);
}


}
}
salam
ki mitonr rahnamaeim kone ke cod haye bala chi kar mikone?
khat be khatesho mikhastam