2013-03-20 151 views
2

我已經搜索了一天中最好的部分,試圖弄清楚這一點,我確定我錯過了某個簡單的解決方案。異步客戶端與表單交互

我正在使用異步套接字客戶端連接來監視來自TCP連接的傳入數據。我已經按照msdn示例的建議實施了ManualResetEvent和Callback方法,但Callback方法無法調用用於將接收到的數據輸出到Windows窗體的方法。如何從套接字接收數據並將其發送到表單中的文本框?

我確定有一個簡單的伎倆,我錯過了某個地方。示例代碼是爲控制檯應用程序編寫的。我如何使表單對來自Socket的傳入數據做出反應?

更新:

我覺得你讓我走上正軌。我試着使用代碼來使用代碼,但我顯然不太瞭解代表的工作方式,因爲它一直拋出以下錯誤:

非靜態字段,方法或屬性' APRS_SMS_Gateway.MainForm.SockOutputDelegate'

你能讓我靠近嗎?這是ConnectCallBack處理程序,我現在正在嘗試工作,但我想使用所有CallBack中的同一個方法(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"); 
    } 



} 

}

+0

由於您的委託需要聲明爲靜態,即靜態void SockOutput(string text),您將得到異常。 – MarcF 2013-03-21 10:44:15

+0

@ user2192887嘗試刪除'static'並嘗試。 – 2013-03-21 11:11:16

+0

@MarcF我嘗試修改代碼來聲明委託爲靜態的,但這並沒有幫助。 – 2013-03-21 14:17:16

回答