2

私はこれを理解しようとして一日の大部分を探しましたが、どこかに簡単な解決策が欠けていると確信しています。

TCP 接続からの受信データを監視するために、非同期ソケット クライアント接続を使用しています。msdn サンプルで推奨されているように、ManualResetEvent と Callback メソッドを実装しましたが、Callback メソッドは、受信したデータを Windows フォームに出力するために使用されるメソッドを呼び出すことができません。ソケットから受信したデータをフォームのテキスト ボックスに送信するにはどうすればよいですか?

どこかに欠けている簡単なトリックがあると確信しています。サンプル コードは、コンソール アプリケーション用に記述されています。ソケットからの受信データにフォームを反応させるにはどうすればよいですか?

アップデート:

あなたは私を正しい軌道に乗せたと思います。デリゲートを使用するコードを挿入しようとしましたが、次のエラーがスローされ続けるため、デリゲートのしくみがよくわかりません。

非静的フィールド、メソッド、またはプロパティ「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");
    }



}

}

4

1 に答える 1

2

ソケット側は正常に機能しているようです。問題の原因となっているwinformを更新するだけです。ここで答えを見つけることができます。別のスレッド_および_クラスからWinFormコントロールを更新します

于 2013-03-20T22:12:56.707 に答える