我有顯示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的最佳實踐是什麼?
您對我的代碼有何看法? 歡迎任何建議。