class testDemo
{
public string ResponseContent;
/// <summary>
/// Get the new data and send it out to all other connections.
/// Note: If not data was recieved the connection has probably
/// died.
/// </summary>
/// <param name="ar"></param>
public void OnRecievedData(IAsyncResult ar)
{
// Socket was the passed in object
Socket sock = (Socket)ar.AsyncState;
// Check if we got any data
try
{
int nBytesRec = sock.EndReceive(ar);
if (nBytesRec > 0)
{
ResponseContent += Encoding.UTF8.GetString(m_byBuff, 0, nBytesRec);
SetupRecieveCallback(sock);
}
else
{
// If no data was recieved then the connection is probably dead
//Console.WriteLine("Client {0}, disconnected", sock.RemoteEndPoint);
sock.Shutdown(SocketShutdown.Both);
sock.Close();
}
}
catch (Exception ex)
{
throw new Exception("\n" + sock.RemoteEndPoint.ToString() + ": Remote servr lost!\n" + ex.Message);
}
}
public GetResponse()
{
.....
AsyncCallback onconnect = new AsyncCallback(OnConnect);
var result = socket.BeginConnect(remoteEP, onconnect, socket);
.....
Send();
.....
}
......
public void OnConnect(IAsyncResult ar)
{
// Socket was the passed in object
Socket sock = (Socket)ar.AsyncState;
// Check if we were sucessfull
try
{
if (sock.Connected)
{
SetupRecieveCallback(sock);
}
else
throw new Exception("Unable to connect to remote machine, Connect Failed!");
}
catch (Exception ex)
{
throw new Exception(ex.Message + "Unusual error during Connect!");
}
}
......
public void SetupRecieveCallback(Socket sock)
{
try
{
AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
var result = sock.BeginReceive(m_byBuff, 0, m_byBuff.Length,
SocketFlags.None, recieveData, sock);
bool success = result.AsyncWaitHandle.WaitOne(Timeout * 1000, true);
}
catch (Exception ex)
{
throw new Exception("\n" + sock.RemoteEndPoint.ToString() + ": nSetup Recieve Callback failed!\n" + ex.Message);
}
}
}
class test2
{
class testDemo = new class testDemo();
// below is main, but because testDemo.OnRecievedData is async, so now testDemo.ResponseContent is null,
// i have to use Thread.Sleep(20 * 1000);
Thread.Sleep(20 * 1000); // max time, wait testDdemo done.
string content = testDemo.ResponseContent;
}
One is main thread, one is async thread, the main thread must wait for async thread to done.
I think there will certainly be a better way, how to solve ?
I need a socket web request class, if you have, please help me ..
From China.