protected Socket _sck;
protected string _host;
protected UInt16 _port;
public void Connect(string RemoteHostIP, UInt16 RemotePort)
{
if (this._sck != null)
{
this._sck.Close();
this._sck = null;
}
this._sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this._host = RemoteHostIP;
this._port = RemotePort;
try
{
this._sck.BeginConnect(new IPEndPoint(IPAddress.Parse(this._host), this._port), new AsyncCallback(this.onSocketConnected), this._sck);
// Raise the event.
this.OnConnectionAttempt(new SocketConnectEventArgs(this._host, this._port));
}
catch (SocketException se)
{
this.OnSocketError(new SocketErrorEventArgs(se.ErrorCode, se.Message));
}
}
-------------------------------------------------------------------------- From There...
private void onDataReceived(IAsyncResult ar)
{
SocketPacket myData = (SocketPacket)ar.AsyncState;
try
{
int bRx = myData.assocSocket.EndReceive(ar);
if (bRx > 0)
{
// Raise the event.
this.OnRecieveData(new SocketRecvEventArgs(bRx, myData.dataBuffer));
// Resume the recv loop.
this.WaitForData();
}
else
{
// Raise the event.
//this.OnDisconnect(new EventArgs());
}
}
catch (SocketException se)
{
this.OnSocketError(new SocketErrorEventArgs(se.ErrorCode, se.Message));
}
catch (ObjectDisposedException oe)
{
// It's dead. We're just still receiving?
}
}
private void onDataSent(IAsyncResult ar)
{
Socket sck = (Socket)ar.AsyncState;
try
{
int bTx = sck.EndSend(ar);
// Raise the event.
this.OnSendData(new SocketSendEventArgs(bTx));
}
catch (SocketException se)
{
this.OnSocketError(new SocketErrorEventArgs(se.ErrorCode, se.Message));
}
}
private void onSocketConnected(IAsyncResult ar)
{
Socket sck = (Socket)ar.AsyncState;
try
{
sck.EndConnect(ar);
// Raise the event.
this.OnConnect(new SocketConnectEventArgs(this._host, this._port));
// Start the receiving loop.
this.WaitForData();
}
catch (SocketException se)
{
this.OnSocketError(new SocketErrorEventArgs(se.ErrorCode, se.Message));
}
}
private void onSocketDisconnected(IAsyncResult ar)
{
Socket sck = (Socket)ar.AsyncState;
try
{
sck.EndDisconnect(ar);
// Raise the event.
this.OnDisconnect(new EventArgs());
}
catch (SocketException se)
{
this.OnSocketError(new SocketErrorEventArgs(se.ErrorCode, se.Message));
}
}