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 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. //
  2. // Client.cs
  3. //
  4. // Author:
  5. // Di MERCURIO Sébastien <dimercur@insa-toulouse.fr>
  6. //
  7. // Copyright (c) 2018 INSA - DGEI
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU General Public License as published by
  11. // the Free Software Foundation, either version 3 of the License, or
  12. // (at your option) any later version.
  13. //
  14. // This program is distributed in the hope that it will be useful,
  15. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. // GNU General Public License for more details.
  18. //
  19. // You should have received a copy of the GNU General Public License
  20. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. using System;
  22. using System.Net.Sockets;
  23. using System.Text;
  24. namespace monitor
  25. {
  26. /// <summary>
  27. /// Static class for TCP client
  28. /// </summary>
  29. public static class Client
  30. {
  31. /// <summary>
  32. /// Default server name
  33. /// </summary>
  34. public const string defaultIP = "localhost";
  35. /// <summary>
  36. /// Default server port number
  37. /// </summary>
  38. public const int defaultPort = 5544;
  39. /// <summary>
  40. /// Tcp client object
  41. /// </summary>
  42. private static TcpClient client = null;
  43. /// <summary>
  44. /// Stream object used for communication
  45. /// </summary>
  46. private static NetworkStream stream = null;
  47. /// <summary>
  48. /// Size of internal buffer used when reading data from server
  49. /// </summary>
  50. private const int BufferMaxSize = 512;
  51. /// <summary>
  52. /// Internal buffer used when reading data from server
  53. /// </summary>
  54. private static byte[] buffer = new byte[BufferMaxSize];
  55. /// <summary>
  56. /// buffer containing received message from TCP server
  57. /// Used to concatenate internal buffers into one
  58. /// </summary>
  59. private static byte[] receiveBuffer;
  60. private static int initialReceiveBufferIndex = 0;
  61. /// <summary>
  62. /// String containing received message from tcp server
  63. /// </summary>
  64. private static StringBuilder message = new StringBuilder();
  65. private static int newLength = 1;
  66. private static int packetCounter = 0;
  67. /// <summary>
  68. /// Callback to send received message to upper level
  69. /// </summary>
  70. public delegate void ReadEvent(string msg, byte[] buffer);
  71. public static ReadEvent readEvent = null;
  72. /// <summary>
  73. /// Open connection to server "host", on default port number.
  74. /// </summary>
  75. /// <returns>true if connection succeded, false otherwise</returns>
  76. /// <param name="host">Hostname to connect to</param>
  77. public static bool Open(string host)
  78. {
  79. return Client.Open(host, defaultPort);
  80. }
  81. /// <summary>
  82. /// Open connection to server "host", with port number "port"
  83. /// </summary>
  84. /// <returns>true if connection succeded, false otherwise</returns>
  85. /// <param name="host">Hostname to connect to</param>
  86. /// <param name="port">Port number for connection</param>
  87. public static bool Open(string host, int port)
  88. {
  89. bool status = true;
  90. try
  91. {
  92. client = new TcpClient(host, port);
  93. stream = client.GetStream();
  94. // Start reading tcp stream and call "ReadCallback" method when newLength data
  95. // will be received
  96. // initially, "newLength" is equal to 1, so first call to ReadCallback
  97. // will be done after reception of 1 byte.
  98. // received data are stored in buffer
  99. // Next reading will be done in ReadCallback method
  100. stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
  101. }
  102. catch (ArgumentNullException e)
  103. {
  104. Console.WriteLine("ArgumentNullException: " + e);
  105. status = false;
  106. }
  107. catch (SocketException e)
  108. {
  109. Console.WriteLine("SocketException: " + e.ToString());
  110. status = false;
  111. }
  112. catch (Exception e)
  113. {
  114. Console.WriteLine("Unknown Exception: " + e.ToString());
  115. status = false;
  116. }
  117. return status;
  118. }
  119. /// <summary>
  120. /// Close connection to server
  121. /// </summary>
  122. public static void Close()
  123. {
  124. if (stream != null) stream.Close();
  125. if (client != null) client.Close();
  126. }
  127. /// <summary>
  128. /// Callback call by stream.BeginRead after reception of newLength data
  129. /// </summary>
  130. /// <param name="ar">Not sure of what is it, but needed for terminate reading</param>
  131. private static void ReadCallback(IAsyncResult ar)
  132. {
  133. if (client.Connected)
  134. {
  135. int bytesRead;
  136. try
  137. {
  138. // Termintae read operation, and get number of byte stored in buffer
  139. bytesRead = stream.EndRead(ar);
  140. }
  141. catch (ObjectDisposedException e)
  142. {
  143. Console.WriteLine("Connection to server dropped: " + e.ToString());
  144. return;
  145. }
  146. newLength = 1;
  147. // if number of byte read is not 0, concatenate string and buffer
  148. if (bytesRead > 0)
  149. {
  150. packetCounter++;
  151. if (packetCounter >= 3)
  152. {
  153. //Console.WriteLine("Supplementary packet " + packetCounter);
  154. }
  155. // Append new data to current string (expecting data are ascii)
  156. message.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
  157. // Similarly, append received bytes to current buffer
  158. if (receiveBuffer == null) receiveBuffer = new byte[bytesRead];
  159. else Array.Resize<byte>(ref receiveBuffer, initialReceiveBufferIndex + bytesRead); // resize currrent buffer
  160. System.Buffer.BlockCopy(buffer, 0, receiveBuffer, initialReceiveBufferIndex, bytesRead); // and add received data
  161. initialReceiveBufferIndex = receiveBuffer.Length; // move last index of current buffer
  162. }
  163. // if it remains received data, prepare for a new reading (get another buffer to append to current one)
  164. if (client.Available > 0)
  165. {
  166. newLength = client.Available;
  167. if (newLength > BufferMaxSize) newLength = BufferMaxSize;
  168. else newLength = client.Available;
  169. }
  170. else
  171. {
  172. // no more data to read, buffer and string can be send to upper level
  173. readEvent?.Invoke(message.ToString(), receiveBuffer);
  174. message.Clear();
  175. receiveBuffer = null;
  176. initialReceiveBufferIndex = 0;
  177. packetCounter = 0;
  178. }
  179. // Prepare for reading new data
  180. if (newLength> BufferMaxSize) newLength = BufferMaxSize;
  181. if (newLength <= 0) newLength = 1;
  182. stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
  183. }
  184. }
  185. /// <summary>
  186. /// Write a string to server
  187. /// </summary>
  188. /// <returns>Nothing</returns>
  189. /// <param name="mes">Message to send to server</param>
  190. public static void Write(string mes)
  191. {
  192. if (client.Connected)
  193. {
  194. byte[] writeBuffer = Encoding.UTF8.GetBytes(mes);
  195. stream.Write(writeBuffer, 0, mes.Length);
  196. }
  197. }
  198. }
  199. }