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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. using System.Threading;
  25. namespace monitor
  26. {
  27. /// <summary>
  28. /// Static class for TCP client
  29. /// </summary>
  30. public static class Client
  31. {
  32. /// <summary>
  33. /// Default server name
  34. /// </summary>
  35. public const string defaultIP = "10.105.1.13";
  36. /// <summary>
  37. /// Default server port number
  38. /// </summary>
  39. public const int defaultPort = 5544;
  40. /// <summary>
  41. /// Tcp client object
  42. /// </summary>
  43. private static TcpClient client = null;
  44. /// <summary>
  45. /// Stream object used for communication
  46. /// </summary>
  47. private static NetworkStream stream = null;
  48. /// <summary>
  49. /// Size of internal buffer used when reading data from server
  50. /// </summary>
  51. private const int BufferMaxSize = 8*1024;
  52. /// <summary>
  53. /// Internal buffer used when reading data from server
  54. /// </summary>
  55. private static byte[] buffer = new byte[BufferMaxSize];
  56. /// <summary>
  57. /// String containing received message from tcp server
  58. /// </summary>
  59. private static StringBuilder message = new StringBuilder();
  60. /// <summary>
  61. /// Callback to send received message to upper level
  62. /// </summary>
  63. public delegate void ReadEvent(string msg);
  64. public static ReadEvent readEvent = null;
  65. /// <summary>
  66. /// Open connection to server "host", on default port number.
  67. /// </summary>
  68. /// <returns>true if connection succeded, false otherwise</returns>
  69. /// <param name="host">Hostname to connect to</param>
  70. public static bool Open(string host)
  71. {
  72. return Client.Open(host, defaultPort);
  73. }
  74. /// <summary>
  75. /// Open connection to server "host", with port number "port"
  76. /// </summary>
  77. /// <returns>true if connection succeded, false otherwise</returns>
  78. /// <param name="host">Hostname to connect to</param>
  79. /// <param name="port">Port number for connection</param>
  80. public static bool Open(string host, int port)
  81. {
  82. bool status = true;
  83. try
  84. {
  85. client = new TcpClient(host, port);
  86. stream = client.GetStream();
  87. // Start reading tcp stream and call "ReadCallback" method when newLength data
  88. // will be received
  89. // initially, "newLength" is equal to 1, so first call to ReadCallback
  90. // will be done after reception of 1 byte.
  91. // received data are stored in buffer
  92. // Next reading will be done in ReadCallback method
  93. stream.BeginRead(buffer, 0, 1, new AsyncCallback(ReadCallback), message);
  94. }
  95. catch (ArgumentNullException e)
  96. {
  97. Console.WriteLine("ArgumentNullException: " + e);
  98. status = false;
  99. }
  100. catch (SocketException e)
  101. {
  102. Console.WriteLine("SocketException: " + e.ToString());
  103. status = false;
  104. }
  105. catch (Exception e)
  106. {
  107. Console.WriteLine("Unknown Exception: " + e.ToString());
  108. status = false;
  109. }
  110. return status;
  111. }
  112. /// <summary>
  113. /// Close connection to server
  114. /// </summary>
  115. public static void Close()
  116. {
  117. if (stream != null) stream.Close();
  118. if (client != null) client.Close();
  119. }
  120. /// <summary>
  121. /// Callback call by stream.BeginRead after reception of newLength data
  122. /// </summary>
  123. /// <param name="ar">Not sure of what is it, but needed for terminate reading</param>
  124. private static void ReadCallback(IAsyncResult ar)
  125. {
  126. int newLength = 1;
  127. int index = -1;
  128. if (client.Connected)
  129. {
  130. int bytesRead;
  131. try
  132. {
  133. // Terminate read operation, and get number of byte stored in buffer
  134. bytesRead = stream.EndRead(ar);
  135. }
  136. catch (ObjectDisposedException e)
  137. {
  138. Console.WriteLine("Connection to server dropped: " + e.ToString());
  139. return;
  140. }
  141. catch (System.IO.IOException e)
  142. {
  143. Console.WriteLine("Connection to server dropped: " + e.ToString());
  144. return;
  145. }
  146. newLength = 1;
  147. index = -1;
  148. // if number of byte read is not 0, concatenate string and buffer
  149. if (bytesRead > 0)
  150. {
  151. //Console.WriteLine("Receive " + bytesRead + " data");
  152. // Append new data to current string (expecting data are ascii)
  153. message.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
  154. index = SearchCarriageReturn(buffer, bytesRead);
  155. }
  156. // if it remains received data, prepare for a new reading (get another buffer to append to current one)
  157. if (index == -1)
  158. {
  159. if (client.Available > 0)
  160. {
  161. newLength = client.Available;
  162. if (newLength > BufferMaxSize) newLength = BufferMaxSize;
  163. else newLength = client.Available;
  164. }
  165. }
  166. else
  167. {
  168. string s = message.ToString();
  169. // no more data to read, buffer and string can be send to upper level
  170. readEvent?.Invoke(s);
  171. message.Clear();
  172. if (index != bytesRead - 1)
  173. {
  174. byte[] trailing=new byte[BufferMaxSize];
  175. Array.Copy(buffer, index + 1, trailing, 0, bytesRead - index - 1);
  176. message.Append(Encoding.ASCII.GetString(trailing, 0, bytesRead - index - 1));
  177. }
  178. }
  179. // Prepare for reading new data
  180. if (newLength> BufferMaxSize) newLength = BufferMaxSize;
  181. if (newLength <= 0) newLength = 1;
  182. try
  183. {
  184. stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
  185. }
  186. catch (ObjectDisposedException e)
  187. {
  188. Console.WriteLine("Connection to server dropped: " + e.ToString());
  189. return;
  190. }
  191. catch (System.IO.IOException e)
  192. {
  193. Console.WriteLine("Connection to server dropped: " + e.ToString());
  194. return;
  195. }
  196. }
  197. }
  198. /// <summary>
  199. /// Searchs the carriage return.
  200. /// </summary>
  201. /// <returns>Index of carriage return, if present, -1 otherwise.</returns>
  202. /// <param name="buf">Buffer of byte</param>
  203. /// <param name="length">Length of buffer</param>
  204. private static int SearchCarriageReturn(byte[] buf, int length)
  205. {
  206. int index = -1;
  207. int i = 0;
  208. for (i = 0; i < length; i++)
  209. {
  210. if (buf[i] == (byte)'\n') break;
  211. }
  212. if (i!= length) index = i;
  213. return index;
  214. }
  215. /// <summary>
  216. /// Write a string to server
  217. /// </summary>
  218. /// <returns>Nothing</returns>
  219. /// <param name="mes">Message to send to server</param>
  220. public static void Write(string mes)
  221. {
  222. if (client.Connected)
  223. {
  224. byte[] writeBuffer = Encoding.UTF8.GetBytes(mes);
  225. stream.Write(writeBuffer, 0, mes.Length);
  226. }
  227. }
  228. }
  229. }