异步客户端与表单交互

时间:2013-03-20 22:00:11

标签: c# winforms sockets asynchronous client

我已经搜索了当天最好的部分,试图解决这个问题,我确信我在某个地方错过了一个简单的解决方案。

我正在使用异步套接字客户端连接来监视来自TCP连接的传入数据。我已经按照msdn示例的建议实现了ManualResetEvent和Callback方法,但是Callback方法无法调用用于将接收到的数据输出到Windows窗体的方法。如何获取从套接字收到的数据,并将其发送到我的表单中的文本框?

我确定有一个简单的伎俩,我在某个地方失踪了。示例代码是为控制台应用程序编写的。如何让表单对来自Socket的传入数据作出反应?

更新

我认为你让我走上正轨。我尝试使用代码来使用委托,但我显然不太了解委托如何工作,因为它不断抛出以下错误:

非静态字段,方法或属性'APRS_SMS_Gateway.MainForm.SockOutputDelegate'

需要对象引用 你能让我离我更近一点吗?这是我正在尝试使用的ConnectCallBack Handler,但我想在所有CallBacks中使用相同的方法(SockOutput)。

public partial class MainForm : Form
{
    private AutoResetEvent receiveNow;

    public delegate void SockOutputDelegatetype(string text); // Define delegate type
    public SockOutputDelegatetype SockOutputDelegate;

    // The port number for the remote device.
    private const int port = 14580;

    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone =
        new ManualResetEvent(false);
    private static ManualResetEvent sendDone =
        new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =
        new ManualResetEvent(false);

    // The response from the remote device.
    private static String response = String.Empty;

    public MainForm()
    {

        InitializeComponent();

        SockOutputDelegate = new SockOutputDelegatetype(SockOutput);

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CommSetting.APRSServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //StartClient();

    }

    private void StartClient()
    {
        try
        {
            IPHostEntry ipHostInfo = Dns.GetHostEntry("rotate.aprs.net");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            //Socket APRSServer = new Socket(AddressFamily.InterNetwork,
            //    SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            CommSetting.APRSServer.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), CommSetting.APRSServer);
            connectDone.WaitOne();

            //Show the connect string from the host
            Receive(CommSetting.APRSServer);
            //receiveDone.WaitOne();

            //Show the connection response
            //SockOutput(response);
        }
        catch (Exception e)
        {
            SockOutput(e.ToString());
        }
    }

    private static void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket APRSServer = (Socket)ar.AsyncState;

            // Complete the connection.
            APRSServer.EndConnect(ar);

            // Signal that the connection has been made.
            connectDone.Set();
        }
        catch (Exception e)
        {
            MainForm.Invoke(MainForm.SockOutputDelegate, e.ToString());
        }
    }

    private static void Receive(Socket client)
    {
        try
        {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            //throw new ApplicationException(e.ToString());
            response = e.ToString();
        }
    }

    private static void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the state object and the client socket 
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                // Get the rest of the data.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            else
            {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1)
                {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            response = e.ToString();
        }
    }


    void SockOutput(string text)
    {
            txtSockLog.AppendText(text);
            txtSockLog.AppendText("\r\n");
    }



}

}

1 个答案:

答案 0 :(得分:2)

听起来你的套接字端工作正常,它只是更新导致问题的winform。您可以在Update WinForm Controls from another thread _and_ class找到答案。

相关问题