c#如何从网页同步套接字异步接收数据

时间:2014-04-09 10:03:06

标签: sockets asyncsocket

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;
}

一个是主线程,一个是异步线程,主线程必须等待异步线程完成。

我认为肯定会有更好的方法,如何解决?

我需要一个套接字Web请求类,如果有,请帮帮我..

来自中国。

0 个答案:

没有答案