TcpConnection.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. using FietsLibrary.JSONObjecten;
  2. using FietsLibrary;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net.Security;
  8. using System.Net.Sockets;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Windows.Forms;
  12. using System.Security.Cryptography.X509Certificates;
  13. using System.Security.Authentication;
  14. using System.IO;
  15. namespace FietsClient
  16. {
  17. public class TcpConnection
  18. {
  19. public TcpClient client;
  20. public bool isConnectedFlag { private set; get; }
  21. private SslStream sslStream;
  22. public CurrentData currentData { private set; get; }
  23. public string userID { private set; get; }
  24. private Thread receiveThread;
  25. public delegate void ChatmassegeDelegate(string[] data);
  26. public event ChatmassegeDelegate IncomingChatmessageEvent;
  27. public TcpConnection()
  28. {
  29. client = new TcpClient();
  30. connect();
  31. }
  32. private void onIncomingChatMessage(string[] data)
  33. {
  34. ChatmassegeDelegate cMD = IncomingChatmessageEvent;
  35. if (cMD != null)
  36. {
  37. cMD(data);
  38. }
  39. }
  40. public bool isConnected()
  41. {
  42. return isConnectedFlag;
  43. }
  44. public void connect()
  45. {
  46. try
  47. {
  48. client.Connect("127.0.0.1", 1288);
  49. // create streams
  50. sslStream = new SslStream(client.GetStream(), false,
  51. new RemoteCertificateValidationCallback(CertificateValidationCallback),
  52. new LocalCertificateSelectionCallback(CertificateSelectionCallback));
  53. bool authenticationPassed = true;
  54. try
  55. {
  56. string serverName = System.Environment.MachineName;
  57. X509Certificate cert = GetServerCert();
  58. X509CertificateCollection certs = new X509CertificateCollection();
  59. certs.Add(cert);
  60. sslStream.AuthenticateAsClient(
  61. serverName,
  62. certs,
  63. SslProtocols.Default,
  64. false); // check cert revokation
  65. }
  66. catch (AuthenticationException)
  67. {
  68. authenticationPassed = false;
  69. }
  70. if (authenticationPassed)
  71. {
  72. receiveThread = new Thread(receive);
  73. receiveThread.Start();
  74. isConnectedFlag = true;
  75. }
  76. }
  77. catch (Exception ex)
  78. {
  79. Console.WriteLine(ex);
  80. Thread.Sleep(1000);
  81. isConnectedFlag = false;
  82. }
  83. }
  84. static X509Certificate CertificateSelectionCallback(object sender,
  85. string targetHost,
  86. X509CertificateCollection localCertificates,
  87. X509Certificate remoteCertificate,
  88. string[] acceptableIssuers)
  89. {
  90. return localCertificates[0];
  91. }
  92. private X509Certificate GetServerCert()
  93. {
  94. X509Certificate cert = new X509Certificate2(
  95. @"testcert.pfx",
  96. "jancoow");
  97. return cert;
  98. }
  99. private bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  100. {
  101. return true;
  102. }
  103. public void disconnect()
  104. {
  105. sslStream.Close();
  106. client.Close();
  107. receiveThread.Abort();
  108. isConnectedFlag = false;
  109. }
  110. public void receive()
  111. {
  112. while (client.Connected)
  113. {
  114. byte[] bytesFrom = new byte[(int)client.ReceiveBufferSize];
  115. try
  116. {
  117. sslStream.Read(bytesFrom, 0, client.ReceiveBufferSize);
  118. }
  119. catch (IOException e)
  120. {
  121. Console.WriteLine(e.StackTrace);
  122. break;
  123. }
  124. string response = Encoding.ASCII.GetString(bytesFrom);
  125. string[] response_parts = response.Split('|');
  126. if (response_parts.Length > 0)
  127. {
  128. switch (response_parts[0])
  129. {
  130. case "0": //login and display correct window after login
  131. if (response_parts.Length == 4)
  132. {
  133. if (response_parts[1] == "1" && response_parts[2] == "1")
  134. {
  135. currentData = new CurrentData(userID);
  136. currentData.isDoctor = true;
  137. SendGet(1);
  138. }
  139. else if (response_parts[2] == "0" && response_parts[1] == "1")
  140. {
  141. currentData = new CurrentData(userID);
  142. currentData.isDoctor = false;
  143. SendGet(1);
  144. }
  145. else
  146. new Login("Geen gebruiker gevonden");
  147. }
  148. break;
  149. case "1":
  150. response_parts[1] = response_parts[1].TrimEnd('\0');
  151. currentData.setSessionList(JsonConvert.DeserializeObject<List<Session>>(response_parts[1]));
  152. if (currentData.isDoctor == true)
  153. {
  154. Form activeForm = Form.ActiveForm;
  155. activeForm.Invoke((MethodInvoker)delegate ()
  156. {
  157. DoctorForm doctorForm = new DoctorForm(this);
  158. activeForm.Hide();
  159. doctorForm.Show();
  160. });
  161. }
  162. else
  163. {
  164. Form activeForm = Form.ActiveForm;
  165. if (activeForm != null)
  166. {
  167. activeForm.Invoke((MethodInvoker)delegate ()
  168. {
  169. PatientForm patientForm = new PatientForm(this);
  170. activeForm.Hide();
  171. patientForm.Show();
  172. });
  173. }
  174. }
  175. break;
  176. case "2":
  177. currentData.GetSessions().Last().AddMeasurement(JsonConvert.DeserializeObject<Measurement>(response_parts[1]));
  178. break;
  179. case "7":
  180. // sender receiver message
  181. onIncomingChatMessage(new string[] { response_parts[1], response_parts[2], response_parts[3].TrimEnd('\0') });
  182. break;
  183. case "8":
  184. if (response_parts[1].TrimEnd('\0') != "-1")
  185. {
  186. DoctorModel.doctorModel.onlinePatients = response_parts[1].TrimEnd('\0').Split('\t').ToList();
  187. }
  188. else if (response_parts[1].TrimEnd('\0') == "-1")
  189. {
  190. DoctorModel.doctorModel.onlinePatients = new List<String>();
  191. }
  192. break;
  193. case "9":
  194. JsonConvert.DeserializeObject<List<User>>(response_parts[1]);
  195. break;
  196. }
  197. }
  198. }
  199. }
  200. public void SendLogin(string username, string password)
  201. {
  202. // send command ( cmdID | username | password )
  203. this.userID = username;
  204. SendString("0|" + username + "|" + password + "|");
  205. }
  206. public void SendGet(int GetWhat)
  207. {
  208. // send command ( cmdID | username )
  209. SendString(GetWhat + "|" + userID + "|");
  210. }
  211. public void SendNewSession()
  212. {
  213. // send command ( cmdID | username )
  214. SendString("3|" + userID + FietsLibrary.JsonConverter.SerializeSession(currentData.GetSessions().Last()) + "|");
  215. }
  216. public void SendNewPatient(User user)
  217. {
  218. // send command ( cmdID | username )
  219. SendString("4|" + user.id + "|" + user.password + "|" + user.age + "|" + user.gender + "|" + user.weight + "|");
  220. }
  221. public void SendNewMeasurement()
  222. {
  223. // send command ( cmdID | username )
  224. SendString("5|" + userID + FietsLibrary.JsonConverter.SerializeLastMeasurement(currentData.GetSessions().Last().GetLastMeasurement()) + "|");
  225. }
  226. public void SendChatMessage(string[] data)
  227. {
  228. String receiverID = data[1];
  229. if (currentData != null)
  230. {
  231. String message = data[0];
  232. // send command ( cmdID | username sender | username receiverID | message )
  233. string protocol = "6|" + this.userID + "|" + receiverID + "|" + message;
  234. SendString(protocol);
  235. }
  236. }
  237. public void SendGetActivePatients()
  238. {
  239. SendString("8|" + userID + "|");
  240. }
  241. public void SendDistance(int distance)
  242. {
  243. SendString("10|" + userID + "|" + distance + "|");
  244. }
  245. public void SendTime(int Minutes, int seconds)
  246. {
  247. SendString("11|" + userID + "|" + Minutes + ":" + seconds + "|");
  248. }
  249. public void SendPower(int power)
  250. {
  251. SendString("12|" + userID + "|" + power + "|");
  252. }
  253. public void SendString(string s)
  254. {
  255. try
  256. {
  257. byte[] b = Encoding.ASCII.GetBytes(s);
  258. sslStream.Write(b, 0, b.Length);
  259. sslStream.Flush();
  260. }
  261. catch (Exception e)
  262. {
  263. Console.WriteLine(e);
  264. }
  265. }
  266. }
  267. }