/// <summary> /// This is a partial implementation of the main method for the Monitoring thread. It will first /// create and send StreamStocksMessage, and then go into a recieve loop until _isMonitoring is /// false /// </summary> /// <param name="state"></param> private void Monitoring(object state) { if (Portfolio == null) { return; } StreamStocksMessage startMessage = new StreamStocksMessage(); foreach (KeyValuePair <string, Stock> kv in Portfolio) { startMessage.Add(kv.Key); } Send(startMessage); while (_isMonitoring) { // Try to receive a TickerMessage and pass it onto the Portfolio for procesing. It will // wait 1000 ms before giving up on the receive attempt. In that caase, the message will // be null and the Portfolio.Update method will do nothing. try { var message = Receive(1000); Portfolio.Update(message); } catch (Exception) { // TODO: Handle the error. For example, you may want to Stop the communicator and log the error } } }
public static StreamStocksMessage Decode(byte[] bytes) { StreamStocksMessage message = null; if (bytes != null && bytes.Length >= 2) { message = new StreamStocksMessage { Symbols = new List<string>() }; BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes)); short count = IPAddress.NetworkToHostOrder(binaryReader.ReadInt16()); for (int i = 0; i < count; i++) { byte[] tmp = binaryReader.ReadBytes(6); if (tmp.Length == 6) { string symbol = Encoding.ASCII.GetString(tmp, 0, 6).Trim(); message.Symbols.Add(symbol); } else { message = null; break; } } } return message; }
/// <summary> /// This method sends a message through the UdpClient to the RemoteEndPoint /// </summary> /// <param name="message"></param> private void Send(StreamStocksMessage message) { if (message == null) { return; } byte[] bytesToSend = message.Encode(); try { _myUdpClient.Send(bytesToSend, bytesToSend.Length, RemoteEndPoint); } catch (Exception) { // TODO: handle the error. For example, you may want to Stop the communicator and log the error } }