123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642 |
- using System;
- using System.Text;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- namespace MessageRouter
- {
- public delegate void OnMessageRouterConnectDelegate(MessageRouterConnection client, bool reconnect);
- public delegate void OnMessageRouterDisconnectDelegate(MessageRouterConnection client, Exception e);
- public delegate void OnMessageRouterPacketReceivedDelegate(MessageRouterConnection client, MessageRouterPacket p);
-
-
-
-
-
-
-
-
-
- public class MessageRouterPacket
- {
- public static int MAX_PACKET_LENGTH = 1024 * 1024;
- public static int LEN_LENGTH = 5;
- public static int CRYPT_FORMAT_LENGTH = 1;
- public static int PIPE_LENGTH = 1;
- public readonly char cryptFormat;
- public readonly byte[] buf;
- public MessageRouterPacket(char cryptFormat, byte[] buf)
- {
- this.cryptFormat = cryptFormat;
- this.buf = buf;
- }
- }
- public class MessageRouterConnection : IDisposable
- {
-
- private IPEndPoint remoteEp;
-
- private int localPort;
-
- private readonly int delay;
-
- private const int DEFAULT_DELAY = 5000;
- #region Property accessor
- public IPEndPoint RemoteEp
- {
- get { return remoteEp; }
- set { remoteEp = value; }
- }
- public int LocalPort
- {
- get { return localPort; }
- }
- #endregion
-
-
-
-
-
- public MessageRouterConnection(IPEndPoint remoteEp)
- : this(remoteEp, DEFAULT_DELAY)
- {
- }
-
-
-
-
-
-
-
- public MessageRouterConnection(IPEndPoint remoteEp, int delay)
- {
- if (delay < 0)
- throw new ArgumentException("Invalid delay");
- this.remoteEp = remoteEp;
- this.delay = delay;
- this.localPort = 0;
- }
-
-
-
-
- public override String ToString()
- {
- return "MessageRouterConnection(" + remoteEp + ", " + state + ")";
- }
- #region Socket event delegates
-
- public OnMessageRouterConnectDelegate OnConnect;
-
- public OnMessageRouterDisconnectDelegate OnDisconnect;
-
- public OnMessageRouterPacketReceivedDelegate OnPacketReceived;
- #endregion
- #region Packet I/O
-
-
-
-
-
- public MessageRouterPacket ReadPacket(Stream s)
- {
-
- int len = ReadLen(s);
- if (len == 0)
- throw new IOException("Message router packet len = 0");
- if (len > MessageRouterPacket.MAX_PACKET_LENGTH)
- throw new IOException("Message router packet len > Max packet size");
-
- if (!ReadPipe(s))
- throw new IOException("Malformed router message");
-
- char cryptFormat = ReadCryptFormat(s);
-
- if (!ReadPipe(s))
- throw new IOException("Malformed router message");
- byte[] buf = new byte[len];
- ReadBytes(s, buf);
- return new MessageRouterPacket(cryptFormat, buf);
- }
- private int ReadLen(Stream s)
- {
- byte[] buf = new byte[MessageRouterPacket.LEN_LENGTH];
- ReadBytes(s, buf);
- Encoding encoding = new ASCIIEncoding();
-
- String str = encoding.GetString(buf).TrimStart('0');
- return Convert.ToInt32(str);
- }
- private char ReadCryptFormat(Stream s)
- {
- byte[] buf = new byte[MessageRouterPacket.CRYPT_FORMAT_LENGTH];
- ReadBytes(s, buf);
- char cf = (char)buf[0];
-
- return cf;
- }
- private bool ReadPipe(Stream s)
- {
- byte[] buf = new byte[MessageRouterPacket.PIPE_LENGTH];
- ReadBytes(s, buf);
- if (buf[0] != 0x7C)
- return false;
- return true;
- }
-
-
-
-
-
- private void ReadBytes(Stream s, byte[] buf)
- {
- if (s == null)
- throw new IOException("Socket closed");
- int n = buf.Length;
- int i = 0;
- while (i < n)
- {
- int k = s.Read(buf, i, n - i);
- if (k == 0)
- throw new IOException("Socket eof");
- i += k;
- }
- }
- private void WriteLen(Stream s, int len)
- {
- byte[] buf = new byte[MessageRouterPacket.LEN_LENGTH];
- String str = len.ToString();
- int padding = MessageRouterPacket.LEN_LENGTH - str.Length;
- for (int i = 0; i < padding; i++)
- str = "0" + str;
- System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
- WriteBytes(s, encoding.GetBytes(str));
- }
- private void WriteCryptFormat(Stream s, char cryptFormat)
- {
- byte[] buf = new byte[MessageRouterPacket.CRYPT_FORMAT_LENGTH];
- buf[0] = (byte)cryptFormat;
- WriteBytes(s, buf);
- }
- private void WritePipe(Stream s)
- {
- byte[] pipe = new Byte[MessageRouterPacket.PIPE_LENGTH];
- pipe[0] = 0x7C;
- WriteBytes(s, pipe);
- }
-
- private void WriteBytes(Stream s, byte[] buf)
- {
- if (s == null)
- throw new IOException("Socket closed");
- s.Write(buf, 0, buf.Length);
- }
-
-
-
-
-
- private void WritePacket(Stream s, MessageRouterPacket p)
- {
- WriteLen(s, p.buf == null ? 0 : p.buf.Length);
- WritePipe(s);
- WriteCryptFormat(s, p.cryptFormat);
- WritePipe(s);
- WriteBytes(s, p.buf);
- s.Flush();
- }
- #endregion
- #region Socket state management
- enum State { CLOSED, OPENING, OPENED };
-
- private State _state;
-
- private State state
- {
- get
- {
- return _state;
- }
- set
- {
- lock (this)
- {
- _state = value;
- Monitor.PulseAll(this);
- }
- }
- }
- #endregion
- #region Connection Management
-
- private TcpClient tcpClient;
-
- private Stream inputStream;
-
- private Stream outputStream;
-
- private bool reconnect;
-
-
-
- private void PrepareToOpen()
- {
- if (state != State.CLOSED)
- throw new InvalidOperationException("Socket already open");
- if (remoteEp == null)
- throw new InvalidOperationException("Invalid remote end point");
- if (OnPacketReceived == null)
- throw new InvalidOperationException("Missing deletegate for packet received event");
- state = State.OPENING;
- }
-
-
-
- private void OpenConnection()
- {
- lock (this)
- {
- if (state != State.OPENING)
- throw new Exception("Socket state not opening - " + state);
- tcpClient = new TcpClient();
- try
- {
- tcpClient.Connect(remoteEp);
- tcpClient.NoDelay = true;
- NetworkStream networkStream = tcpClient.GetStream();
- inputStream = new BufferedStream(networkStream);
- outputStream = new BufferedStream(networkStream);
- state = State.OPENED;
- IPEndPoint localEndPoint = tcpClient.Client.LocalEndPoint as IPEndPoint;
- localPort = localEndPoint.Port;
- if (OnConnect != null)
- OnConnect(this, reconnect);
- reconnect = true;
- }
- catch (Exception e)
- {
- CloseConnection(e);
- throw e;
- }
- }
- }
-
-
-
- private void ReadConnection()
- {
- Stream xis = inputStream;
- if (xis == null)
- return;
- while (state == State.OPENED)
- {
- MessageRouterPacket p = ReadPacket(xis);
- if (OnPacketReceived != null)
- OnPacketReceived(this, p);
- }
- }
-
-
-
-
- private void CloseConnection(Exception e)
- {
- lock (this)
- {
- if (tcpClient != null)
- {
- if (inputStream != null)
- {
- try
- {
- inputStream.Close();
- }
- catch { }
- inputStream = null;
- }
- if (outputStream != null)
- {
- try
- {
- outputStream.Close();
- }
- catch { }
- outputStream = null;
- }
- try
- {
- tcpClient.Close();
- }
- catch { }
- tcpClient = null;
- localPort = 0;
- if (state == State.OPENED)
- state = State.OPENING;
- if (OnDisconnect != null)
- OnDisconnect(this, e);
- }
- }
- }
-
-
-
- public void Dispose()
- {
- Close(1);
- }
- #endregion
- #region Asynchronous Session Management
-
-
-
- public void Start()
- {
- lock (this)
- {
- PrepareToOpen();
- thread = StartThread(new ThreadStart(Run), "Run");
- }
- }
-
-
-
- private void Run()
- {
- while (state != State.CLOSED)
- {
- OpenConnectionX();
- try
- {
- ReadConnection();
- CloseConnection(null);
- }
- catch (ThreadAbortException)
- {
- }
- catch (Exception e)
- {
- CloseConnection(e);
- }
- }
- }
-
-
-
- private void OpenConnectionX()
- {
- while (state == State.OPENING)
- {
- lock (this)
- {
- try
- {
- OpenConnection();
- return;
- }
- catch (SocketException)
- {
- if (state == State.OPENING)
- Monitor.Wait(this, delay);
- }
- }
- }
- }
-
-
-
- public void Close()
- {
- Close(0);
- }
-
-
-
-
- public void Close(int timeout)
- {
- if (timeout < 0)
- throw new ArgumentException("Invalid timeout value");
- lock (this)
- {
- if (state != State.CLOSED)
- {
- state = State.CLOSED;
- CloseConnection(new Exception("Socket closed"));
- }
- }
- if (thread != Thread.CurrentThread)
- {
- StopThread(thread, timeout);
- thread = null;
- }
- }
- #endregion
- #region Synchronous Session Management
-
-
-
-
- public bool Open()
- {
- lock (this)
- {
- try
- {
- PrepareToOpen();
- OpenConnection();
- thread = StartThread(new ThreadStart(SyncReader), "SyncReader");
- return true;
- }
- catch (SocketException e)
- {
- state = State.CLOSED;
- CloseConnection(e);
- return false;
- }
- }
- }
-
-
-
- private void SyncReader()
- {
- try
- {
- ReadConnection();
- FinishSyncReader(null);
- }
- catch (Exception e)
- {
- FinishSyncReader(e);
- }
- }
-
-
-
-
- private void FinishSyncReader(Exception e)
- {
- lock (this)
- {
- if (state != State.CLOSED)
- {
- state = State.CLOSED;
- CloseConnection(e);
- thread = null;
- }
- }
- }
- #endregion
- #region Thread Management
-
- private Thread thread;
-
-
-
-
-
-
- private Thread StartThread(ThreadStart start, string what)
- {
- Thread t = new Thread(start);
- t.IsBackground = true;
- t.Name = ToString() + " " + what;
- t.Start();
- return t;
- }
-
-
-
-
-
- private void StopThread(Thread t, int timeout)
- {
- if (t == null)
- return;
- if (!t.Join(timeout))
- t.Abort();
- }
- #endregion
- #region Outgoing Data
- public bool Write(char cryptFormat, byte[] data)
- {
- try
- {
- MessageRouterPacket p = new MessageRouterPacket(cryptFormat, data);
- lock (writeSync)
- {
- WritePacket(outputStream, p);
- }
- }
- catch (Exception e)
- {
- CloseConnection(e);
- return false;
- }
- return true;
- }
- private Object writeSync = new Object();
- #endregion
- }
- }
|