2012-03-06 113 views
0

我有顯示varios事件的asp.net mvc應用程序。所有事件存儲在數據庫中。但現在,我必須從數據庫和遠程程序中加載數據。這個程序有外部服務(這是一個簡單的程序,它監聽特定的端口並接收查詢並返回xml)。在asp.net mvc應用程序中的TCPClient

而且,我寫了簡單的測試頁面,連接到外部程序。將代碼從MSDN獲得:

static string Connect(String server, String message) 
{ 
    try 
    { 
    // Create a TcpClient.   
    Int32 port = 9197; 
    TcpClient client = new TcpClient(server, port); 

    // Translate the passed message into ASCII and store it as a Byte array. 
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);   

    // Get a client stream for reading and writing. 
    // Stream stream = client.GetStream(); 

    NetworkStream stream = client.GetStream(); 

    // Send the message to the connected TcpServer. 
    stream.Write(data, 0, data.Length); 

    // Receive the TcpServer.response. 

    // Buffer to store the response bytes. 
    data = new Byte[256]; 

    // String to store the response ASCII representation. 
    String responseData = String.Empty; 

    // Read the first batch of the TcpServer response bytes. 
    Int32 bytes = stream.Read(data, 0, data.Length); 
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);     


    stream.Close();   
    client.Close(); 
    return responseData; 
    } 
    catch (ArgumentNullException e) 
    { 
    // 
    } 
    catch (SocketException e) 
    { 
    // 
    } 

} 

這是我的行動:

public ActionResult GetData() 
     {   

      string query = "some query"; 

      var response = Connect("192.168.0.1", query); 
      var model = ParseResponse(response); 
      return View(model); 
     } 

我覺得這個解決方案將降低更流暢。

在ASP.NET MVC 3應用程序中使用TCPClient的最佳實踐是什麼?
您對我的代碼有何看法? 歡迎任何建議。

回答

1

我覺得這個解決方案會降低性能。

好吧。所有/大部分數據庫操作都通過套接字完成。你沒有注意到,是嗎?

最可能的性能問題:

  1. 您的服務器
  2. 服務器位置
  3. 連接設置

我現在唯一要做的是檢查,建立在客戶端在響應時間過長時監視響應時間並寫入日誌(或發送電子郵件)。

在這種情況發生之前不要試圖優化性能。

解決方案上面提到的問題:

  1. 重構和優化
  2. 要麼把服務器上的同一個局域網或創建一個高速緩存代理服務器。
  3. 使用連接池而不是每次斷開連接。
0

我認爲這個解決方案會降低性能。

它與您的服務器執行的任何其他遠程請求 - I/O密集型操作一樣。所以你可以使用asynchronous controller和TcpClient方法的異步版本。這樣,在執行遠程請求期間,您不會危害服務器上的任何工作線程。