/* * MonitorThread method */ protected static void monitorMethod() { while (!_monitorStop) { _monitorMutex.WaitOne(); IEnumerator e = _connections.GetEnumerator(); while (e.MoveNext()) { Connection c = (Connection)e.Current; if (c.ReconnectRequested()) { c._socketMutex.WaitOne(); c.Disconnect(); c.Connect(); if (c.IsConnected()) { c._reconnect = false; Globals.AddEventCallback(new ConnRegainDispatcher(c)); } c._socketMutex.ReleaseMutex(); } } _monitorMutex.ReleaseMutex(); Thread.Sleep(1000); } }
/* * Receive methods */ protected void receiveMethod() { Message msg = null; byte[] buf = new byte[65536]; byte[] num = new byte[4]; int bytesRead = 0; int len = 0; int xmllen = 0; byte[] oldbuf = buf; _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); while (!_receiveStop) { try { if (ReconnectRequested()) { Thread.Sleep(1000); continue; } // the receive process works in three steps // 1. Get the length of the message (4 bytes) // 2. Get the length of the xml portion (4 bytes) // 3. Get the message data // make sure that a reconnection isn't somehow in progress _socketMutex.WaitOne(); // STEP #1: Read length value len = 0; while (true) { len += _socket.Receive(num, len, 4 - len, SocketFlags.None); if (len == 4) { len = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(num, 0)); break; } } // STEP #2: Read XML length value xmllen = 0; while (true) { xmllen += _socket.Receive(num, xmllen, 4 - xmllen, SocketFlags.None); if (xmllen == 4) { xmllen = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(num, 0)); if (xmllen > len) { throw new IOException("XML length cannot exceed message length"); } break; } } // STEP #3: Read Message Data // check to see if we need a longer buffer for this message, and create // one if needed if (len > buf.Length) { buf = new byte[len]; } bytesRead = 0; while (true) { bytesRead += _socket.Receive(buf, bytesRead, len - bytesRead, SocketFlags.None); if (bytesRead == len) { // get the xml data into usable form string result = System.Text.Encoding.ASCII.GetString(buf, 0, xmllen); XmlTextReader xml = new XmlTextReader(new StringReader(result)); // get binary data into usable form (if necessary) MemoryStream binaryData = null; if (len > xmllen) { byte[] binbuf = new byte[len - xmllen]; Array.Copy(buf, xmllen, binbuf, 0, len - xmllen); binaryData = new MemoryStream(binbuf, 0, binbuf.Length, false, true); } msg = Message.Decode(xml, binaryData); if (msg != null && msg.IsValid()) { Globals.AddEventCallback(new MessageDispatcher(this, msg)); } break; } } buf = oldbuf; _socketMutex.ReleaseMutex(); } catch (Exception) { if (!_receiveStop) { RequestReconnect(); Globals.AddEventCallback(new ConnLostDispatcher(this)); } try { // release if we're still holding it _socketMutex.ReleaseMutex(); } catch (ApplicationException) { } } } }
public override void Send(PUC.Communication.Message msg) { ((IDevice2)_frame).HandleMessage(this, msg); Globals.AddEventCallback(new MessageDispatcher(this, msg)); }