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

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