我想創建一個新的系統,以發送實時交易執行消息給使用SignalR的用戶。在舊系統中,每個客戶端使用Java Applet TCP連接連接到交易服務器。使用SignalR發送實時通知
我用下面的教程作爲參考 http://www.asp.net/signalr/overview/getting-started/tutorial-server-broadcast-with-signalr
有代碼在StockTicker構造線更新股票價格:
_timer = new Timer(UpdateStockPrices, null, _updateInterval, _updateInterval);
不過,我需要實時更新交易執行而不是每250毫秒更新一次股票價格。 可以在構造函數中爲每個客戶端的交易服務器創建TCP連接嗎?看起來在示例代碼中,StockTicker的構造函數(即我的TradingManager)只會被調用一次。但在我的設計中,我想爲每個客戶端創建一個TCP連接。我應該如何更改代碼來執行此操作?
這裏是我的代碼:
TradingHub.cs
public class TradingHub : Hub
{
private readonly TradingManager _tradingManager;
public TradingHub() : this(TradingManager.Instance) { }
public TradingHub(TradingManager tradingManager)
{
_tradingManager = tradingManager;
}
...
}
TradingManager.cs
public class TradingManager
{
// Singleton instance
private readonly static Lazy<TradingManager> _instance = new Lazy<TradingManager>(
() => new TradingManager());
...
public static TradingManager Instance{ get{ return _instance.Value; } }
public TradingManager()
{
...
this.apiConnector.MessageReceived += new CustomEventHandler(this.api_MessageReceived);
init();
}
private IHubConnectionContext<dynamic> Clients { get; set; }
private void init()
{
TradingSession tradingSession = getLoginSession(user);
// connect to trading server using TCP connection
this.apiConnector.ensureConnected(host, port, tradingSession);
// send keep alive message to trading server periodically
_timer = new Timer(sendKeepAlive, null, _updateInterval, _updateInterval);
}
private void api_MessageReceived(object sender, CustomEventArgs e)
{
// when web server receives trade execution from server, send out the message immediately
Clients.Caller.SendTradeExecutionMessage(......);
}
public static TradingSession getLoginSession(string user)
{
...
}
private void sendKeepAlive(object state)
{
...
}
}