No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Client.cs 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. using System;
  2. using System.Net.Sockets;
  3. using System.Text;
  4. namespace monitor
  5. {
  6. /// <summary>
  7. /// Static class for TCP client
  8. /// </summary>
  9. public static class Client
  10. {
  11. /// <summary>
  12. /// Default server name
  13. /// </summary>
  14. public const string defaultIP = "localhost";
  15. /// <summary>
  16. /// Default server port number
  17. /// </summary>
  18. public const int defaultPort = 4500;
  19. /// <summary>
  20. /// Tcp client object
  21. /// </summary>
  22. private static TcpClient client = null;
  23. /// <summary>
  24. /// Stream object used for communication
  25. /// </summary>
  26. private static NetworkStream stream = null;
  27. /// <summary>
  28. /// Size of internal buffer used when reading data from server
  29. /// </summary>
  30. private const int BufferMaxSize = 512;
  31. /// <summary>
  32. /// Internal buffer used when reading data from server
  33. /// </summary>
  34. private static byte[] buffer = new byte[BufferMaxSize];
  35. /// <summary>
  36. /// buffer containing received message from TCP server
  37. /// Used to concatenate internal buffers into one
  38. /// </summary>
  39. private static byte[] receiveBuffer;
  40. private static int initialReceiveBufferIndex = 0;
  41. /// <summary>
  42. /// String containing received message from tcp server
  43. /// </summary>
  44. private static StringBuilder message = new StringBuilder();
  45. private static int newLength = 1;
  46. private static int packetCounter = 0;
  47. /// <summary>
  48. /// Callback to send received message to upper level
  49. /// </summary>
  50. public delegate void ReadEvent(string msg, byte[] buffer);
  51. public static ReadEvent readEvent = null;
  52. /// <summary>
  53. /// Open connection to server "host", on default port number.
  54. /// </summary>
  55. /// <returns>true if connection succeded, false otherwise</returns>
  56. /// <param name="host">Hostname to connect to</param>
  57. public static bool Open(string host)
  58. {
  59. return Client.Open(host, defaultPort);
  60. }
  61. /// <summary>
  62. /// Open connection to server "host", with port number "port"
  63. /// </summary>
  64. /// <returns>true if connection succeded, false otherwise</returns>
  65. /// <param name="host">Hostname to connect to</param>
  66. /// <param name="port">Port number for connection</param>
  67. public static bool Open(string host, int port)
  68. {
  69. bool status = true;
  70. try
  71. {
  72. client = new TcpClient(host, port);
  73. stream = client.GetStream();
  74. // Start reading tcp stream and call "ReadCallback" method when newLength data
  75. // will be received
  76. // initially, "newLength" is equal to 1, so first call to ReadCallback
  77. // will be done after reception of 1 byte.
  78. // received data are stored in buffer
  79. // Next reading will be done in ReadCallback method
  80. stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
  81. }
  82. catch (ArgumentNullException e)
  83. {
  84. Console.WriteLine("ArgumentNullException: " + e);
  85. status = false;
  86. }
  87. catch (SocketException e)
  88. {
  89. Console.WriteLine("SocketException: " + e.ToString());
  90. status = false;
  91. }
  92. catch (Exception e)
  93. {
  94. Console.WriteLine("Unknown Exception: " + e.ToString());
  95. status = false;
  96. }
  97. return status;
  98. }
  99. /// <summary>
  100. /// Close connection to server
  101. /// </summary>
  102. public static void Close()
  103. {
  104. if (stream != null) stream.Close();
  105. if (client != null) client.Close();
  106. }
  107. /// <summary>
  108. /// Callback call by stream.BeginRead after reception of newLength data
  109. /// </summary>
  110. /// <param name="ar">Not sure of what is it, but needed for terminate reading</param>
  111. private static void ReadCallback(IAsyncResult ar)
  112. {
  113. if (client.Connected)
  114. {
  115. int bytesRead;
  116. try
  117. {
  118. // Termintae read operation, and get number of byte stored in buffer
  119. bytesRead = stream.EndRead(ar);
  120. }
  121. catch (ObjectDisposedException e)
  122. {
  123. Console.WriteLine("Connection to server dropped: " + e.ToString());
  124. return;
  125. }
  126. newLength = 1;
  127. // if number of byte read is not 0, concatenate string and buffer
  128. if (bytesRead > 0)
  129. {
  130. packetCounter++;
  131. if (packetCounter >= 3)
  132. {
  133. //Console.WriteLine("Supplementary packet " + packetCounter);
  134. }
  135. // Append new data to current string (expecting data are ascii)
  136. message.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
  137. // Similarly, append received bytes to current buffer
  138. if (receiveBuffer == null) receiveBuffer = new byte[bytesRead];
  139. else Array.Resize<byte>(ref receiveBuffer, initialReceiveBufferIndex + bytesRead); // resize currrent buffer
  140. System.Buffer.BlockCopy(buffer, 0, receiveBuffer, initialReceiveBufferIndex, bytesRead); // and add received data
  141. initialReceiveBufferIndex = receiveBuffer.Length; // move last index of current buffer
  142. }
  143. // if it remains received data, prepare for a new reading (get another buffer to append to current one)
  144. if (client.Available > 0)
  145. {
  146. newLength = client.Available;
  147. if (newLength > BufferMaxSize) newLength = BufferMaxSize;
  148. else newLength = client.Available;
  149. }
  150. else
  151. {
  152. // no more data to read, buffer and string can be send to upper level
  153. readEvent?.Invoke(message.ToString(), receiveBuffer);
  154. message.Clear();
  155. receiveBuffer = null;
  156. initialReceiveBufferIndex = 0;
  157. packetCounter = 0;
  158. }
  159. // Prepare for reading new data
  160. stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
  161. }
  162. }
  163. /// <summary>
  164. /// Write a string to server
  165. /// </summary>
  166. /// <returns>Nothing</returns>
  167. /// <param name="mes">Message to send to server</param>
  168. public static void Write(string mes)
  169. {
  170. if (client.Connected)
  171. {
  172. byte[] writeBuffer = Encoding.UTF8.GetBytes(mes);
  173. stream.Write(writeBuffer, 0, mes.Length);
  174. }
  175. }
  176. }
  177. }